-
Looping problem
Where am I going wrong?
I am reading a file using gets() with a for loop and printing the string using strtok with a while() loop.
Can anyone tell me where I am going wrong?
Code:
#include <stdio.h>
#include <string.h>
int main()
{
char customerString[1047];
char *tokenPtr;
int k;
char ch;
printf("Login Id User Id Group Id User Name User Home Directory Starting Shell\n",
"", "", "", "");
for( k = 0; k < 7; k++)
{
gets(customerString);
}
tokenPtr = strtok(customerString, ":");
while ( tokenPtr != NULL)
{
printf("%s \t", tokenPtr);
tokenPtr = strtok(NULL, ":");
}
ch = getchar();
return 0;
}//End main
Example input:
[code]
ceva8710:x:1007:100:ahmadmateen:/home/students/ceva8710:/bin/sh
[\code]
-
Code:
for( k = 0; k < 7; k++)
{
gets(customerString);
}
I think that will only get the last input. You need to use strcat to append input to an array. Try that first. I'm not sure if the strtok is correct because I have not used it in a while.
-
Re: Looping problem
for( k = 0; k < 7; k++)
{
gets(customerString);
}
the above code doesnt make sense , you are reading strings from the standard input seven times and storing them in the same buffer , only the last one stays stored . It is usually better to use fgets than gets .
Quote:
Originally posted by sketchit
Where am I going wrong?
I am reading a file using gets() with a for loop and printing the string using strtok with a while() loop.
Can anyone tell me where I am going wrong?
Code:
#include <stdio.h>
#include <string.h>
int main()
{
char customerString[1047];
char *tokenPtr;
int k;
char ch;
printf("Login Id User Id Group Id User Name User Home Directory Starting Shell\n",
"", "", "", "");
for( k = 0; k < 7; k++)
{
gets(customerString);
}
tokenPtr = strtok(customerString, ":");
while ( tokenPtr != NULL)
{
printf("%s \t", tokenPtr);
tokenPtr = strtok(NULL, ":");
}
ch = getchar();
return 0;
}//End main
Example input:
[code]
ceva8710:x:1007:100:ahmadmateen:/home/students/ceva8710:/bin/sh
[\code]