假设我需要读入两个名字,比如,[name name]\n ....(可能更多的[name name]\n。假设名称的长度为19,那么到目前为止,我的代码是,在我的例子中,如何实际阻止像[name name name]\n或更多的[name name name...]\n这样的输入呢?我听说过fgets()和fscanf,但是谁能给我举一个如何使用它们的例子?提前谢谢。
char name1[20];
char name2[20];
for(int i=0; i < numberOfRow ; i++){
scanf(" %s %s", name1, name2);
}好的,我找到了一种方法来确保只有两个元素,但我不确定如何将它们放回变量中……
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];}
发布于 2011-05-12 21:50:06
您可以使用strtok (string.h.h)。请注意,此函数将修改您的源字符串(您可以复制之前的字符串)。
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;另外,我认为你应该检查
发布于 2011-05-12 19:30:13
如果你从标准输入开始,没有办法阻止它,用户可以输入他们喜欢的内容。最好先读入所有的输入,然后检查,再检查结果。
发布于 2011-05-12 19:31:58
您可以使用fgets读取所有行,然后解析结果。例如:
char name[256];
for (int i = 0; i < numberOfRow; i++)
{
if (fgets(name, 256, stdin) != NULL)
{
// Parse string
}
}fgets读取行,直到按Enter键为止。现在你需要解析这个字符串,如果用户输入错误的输入(如"aaa“或”“)返回错误,否则( "aaa”),拆分字符串并使用"aaa“作为name1和" bbb”作为name2
https://stackoverflow.com/questions/5977106
复制相似问题