Strings, gets and do while

筅森魡賤 提交于 2019-12-02 13:51:09

Your first and most obvious problem is with the left over newline. When you use scanf() here:

    printf("\nDo you want write another text? (1=yes) -> ");
    scanf("%d", &j);
}

and you use the %d format specificer, the function is looking for a number, when you enter a number really you're entering a number and a newline character

> 1<enter key>   // which means on stdin you're getting   '1''\n'

scanf() only picks up the 1 and leaves the newline which your gets() function then picks up, so it looks like it's skipping the input. All you need to do is consume that newline character, one quick fix would be to consume it with getchar():

    printf("\nDo you want write another text? (1=yes) -> ");
    scanf("%d", &j);
    getchar();
}

Now your program works as you'd expect.


Other issues of note:

  1. Your main should really be returning an int type, even if it's just a return 0
  2. You shouldn't be using gets(), even then man page for gets() says Never use gets(). That's usually a good indication not to. ;) So replace that line with fgets(testo, sizeof(testo), stdin);
  3. You missed a performance specificer here: printf("\nThe text is composed by % characters\n", cch); so you're getting garbage output, that should have been %d

It's because the scanf call at the end of the loop doesn't read the newline. Instead this newline is read by your gets call.

A simple solution is to add a space to the end of the scanf format string, like so:

scanf("%d ", &j);

This will make scanf skip trailing whitespace in the input.

Another solution is to put an extra fgets after the scanf, but then don't add the extra space in the format string:

scanf("%d", &j);
fgets(testo, sizeof(testo), stdin);

Or use fgets to get the line, and then use sscanf to extract the answer:

fgets(testo, sizeof(testo), stdin);
sscanf(testo, "%d", &j);

Or you can try using the function flushall() just before gets()

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!