且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

scanf()函数不读取输入字符串当空字符串的早期定义的数组的第一个字符串

更新时间:2023-11-13 23:07:28

其实,你得到它错了我的兄弟。初始化 str_arr 不影响的工作scanf()的,它可能不过似乎你这样的,但它实际上不是。正如在其他的答案中描述过这个叫未定义行为即可。一个的在C本身未定义行为很模糊定义

的C FAQ定义这样的未定义行为:


  

任何事情都有可能发生;标准并没有规定要求。该
  程序可能无法编译,或者它可能不正确地执行(或者
  崩溃或静默产生不正确的结果),或者它可
  偶然做程序员意图到底是什么。


块引用>

它主要是指任何事情都有可能发生。当你做这样的:

 的char * str中;
  scanf函数(%S,STR);

它的一个UB。有时你会得到你不应该成果,你认为它working.That的调试器哪里进来的几乎每一次handy.Use他们,尤其是在开始。其他推荐w.r.t程序:


  • 代替scanf函数的()使用与fgets()阅读字符串。如果你想用scanf函数然后使用它像 scanf函数(%WS,名); 其中name是字符数组和是W 是字段宽度。

  • 编译使用的 -Wall 选项让所有的警告,如果你要使用它,你可能已经得到了您正在使用STR未初始化的警告

在阅读这篇文章去,它有足够的信息来清楚你的疑惑。

I defined an array for strings. It works fine if I define it in such a way the first element is not an empty string. When its an empty string, the next scanf() for the other string stops reading the input string and program stops execution.

Now I don't understand how can defining the array of strings affect reading of input by scanf().

  char *str_arr[] = {"","abc","","","b","c","","",""}; // if first element is "abc" instead of "" then works fine

  int size = sizeof(str_arr)/sizeof(str_arr[0]);

  int i;

  printf("give string to be found %d\n",size);


  char *str;
  scanf("%s",str);
  printf("OK\n");

Actually, you are getting it wrong my brother. The initialization of str_arr doesn't affect the working of scanf() , it may however seem to you like that but it ain't actually. As described in other answers too this is called undefined behavior. An undefined behavior in C itself is very vaguely defined .

The C FAQ defines "undefined behavior" like this:

Anything at all can happen; the Standard imposes no requirements. The program may fail to compile, or it may execute incorrectly (either crashing or silently generating incorrect results), or it may fortuitously do exactly what the programmer intended.

It basically means anything can happen. When you do it like this :

char *str;
  scanf("%s",str);

Its an UB. Sometimes you get results which you are not supposed to and you think its working.That's where debuggers come in handy.Use them almost every time, especially in the beginning. Other recommendation w.r.t your program:

  • Instead of scanf() use fgets() to read strings. If you want to use scanf then use it like scanf("%ws",name); where name is character array and w is the field width.
  • Compile using -Wall option to get all the warnings, if you would have used it, you might have got the warning that you are using str uninitialized.

Go on reading THIS ARTICLE, it has sufficient information to clear your doubts.