I have to make a for loop which counts the letters/digits in the first argument,eg. if i type 'what' 4 will be displayed. currently when i input what i get
0
1
2
3
plz help
#include "stdafx.h"
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
int i;
for (int i = 0; argv[1][i] != '\0'; i++)
cout << i << endl;
}
You need to declare a counter variable for digits and letters and inside your for loop you increment the counter depending on the current char. To check if the character is a letter or digit you can use isdigit and isalpha.
Note in the original code. you have two separate variables named i. The int i outside the for loop has a separate existence to the int i inside the loop.
1 2 3
int i;for (int i = 0; argv[1][i] != '\0'; i++)
cout << i << endl;
Try changing this:
1 2 3
int i;
for (int i = 0; argv[1][i] != '\0'; i++)
cout << i << endl;
to this:
1 2 3 4 5
int i;
for (i = 0; argv[1][i] != '\0'; i++)
; // empty do-nothing statement
cout << i << endl;
or even this:
1 2 3 4 5
int i = 0;
while (argv[1][i])
i++;
cout << i << endl;