scanf to fgets C
Say I need to read in two name
like, [name na开发者_如何学编程me]\n
.... (possibly
more [name name]\n
. Assuming the name
can have length of 19, my code so far
is, How would I actually prevent an input like [name name name]\n
or more [name name name...]\n
in my case ? I heard about fgets() and fscanf but would anyone kindly show me an example how to use them? Thanks in advance.
char name1[20];
char name2[20];
for(int i=0; i < numberOfRow ; i++){
scanf(" %s %s", name1, name2);
}
Ok So I found a way to make sure there is only two element, but I am not sure how to put them back into variable...
char str[50];
int i;
int count = 0;
fgets(str, 50, stdin);
i = strlen(str)-1;
for(int x=0; x < i ;x++){
if(isspace(str[x]))
count++;
}
if(counter > 1){
printf("Error: More than 2 elements.\n");
}else if{
//How do i place those two element back into the variable ?
char name1[20];
char name2[20];
}
You can use strtok (string.h). Please be careful, this function will modify your source string (you may copy the string before).
Example for strtok:
char* word;
// First word:
word = strtok(str, " "); // space as the delimiter
strncpy(name1, word, sizeof(name1) - 1);
name1[sizeof(name1) - 1] = 0; // end of word, in case the word size is > sizeof(name1)
// Second word
word = strtok (NULL, " ");
strncpy(name2, word, sizeof(name2) - 1);
name2[sizeof(name2) - 1] = 0;
Also, I think you should chec
If you are going from standard input, there is no way of stopping this, the user can enter what they like. It would be preferable to read in all the input first then check then result.
You can use fgets to read all the line, and then parse the results. for example:
char name[256];
for (int i = 0; i < numberOfRow; i++)
{
if (fgets(name, 256, stdin) != NULL)
{
// Parse string
}
}
fgets reads the line, until Enter is pressed. Now you need to parse this string, if user enter wrong input (as "aaa" or "aaa bbb ccc") return error, else ("aaa bbb"), split the string and use "aaa" as name1 and "bbb" as name2
精彩评论