Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 读取多个字符串_C_Scanf - Fatal编程技术网

C 读取多个字符串

C 读取多个字符串,c,scanf,C,Scanf,所以我创建了一个c程序,它读取一个查询文件,该文件中填充了要在表上执行的命令。所以我用了: char command[100]; while(1) { fscanf(query, "%s", command); x=strcmp(command, "select"); //continue with checking for other commands etc. //if the command is stop then the loop breaks } 我

所以我创建了一个c程序,它读取一个查询文件,该文件中填充了要在表上执行的命令。所以我用了:

char command[100];
while(1)
{
    fscanf(query, "%s", command);
    x=strcmp(command, "select");
    //continue with checking for other commands etc.
    //if the command is stop then the loop breaks
}

我的问题是,当我第一次调用fscanf时,我知道它会将命令保存到命令数组中。但是我应该把字符串设为“空”还是设为null作为更好的方式?我不确定在使用strcmp或通常使用fscanf覆盖数组时是否有必要。谢谢大家!

您不应该担心会被覆盖的内容。在使用它的值之前,您应该只(始终)担心初始化它。因为否则它是未定义的行为

更重要的是,您应该始终检查在内存上运行的函数的返回值。你永远不能指望“那会有用的”。因为一段时间后,你会突然发现分割错误,不知道如何修复它

如果你不知道怎么做:

int check;

check = fscanf(query, "%s", command);
if(check == EOF)
    perror("fscanf");

您应该做的是测试来自fscanf的返回值;其他任何事情都会带来惊喜,比如非终止循环。您不必担心清除数组。但是还有其他一些事情需要担心,一般来说是
fscanf
,特别是
%s
fgets可能是一个更好的选择;while(fscanf(query,“%99s”,command)=1{…}
将确保更安全的编码。@Jens这会起作用,但我有多个具有相同数量字符的命令…numRows、rowStat、numCols等。谢谢您的帮助suggestion@SteveSummit你能解释一下吗?对我来说(这可能是不正确的),我认为他们做了几乎相同的事情