奇怪的 c++输入转义和空间行为

发布于 2024-09-06 10:59:37 字数 689 浏览 8 评论 0原文

我的 c++ 示例遇到了一个令人不快的问题。一切正常,直到我输入带有空格的内容。

#include <iostream>
using namespace std;

int main (int argc, char * const argv[])
{
    int iteration = 0;
    while (true) {
        char * input = new char[256];
        scanf("%s", input);
        cout << ++iteration << ": " << input << endl;
        cin.get();
    }
    return 0;
}

因此,使用这段代码,我可以输入任何内容,但是空格之后的所有内容都以某种方式存储在缓冲区中并在第二次迭代中使用。

foo
1: foo
bar
2: bar
foobar
3: foobar
foo bar
4: foo
5: bar

每个输入读取功能都是这样的,这让我发疯。 cin>> inputfreads()cin.get() 等都执行此操作。

这是用户输入的常见问题,还是我在这里做错了什么?

I'm having an unpleasant problem with my c++ example. Everything works fine until I enter something with a whitespace.

#include <iostream>
using namespace std;

int main (int argc, char * const argv[])
{
    int iteration = 0;
    while (true) {
        char * input = new char[256];
        scanf("%s", input);
        cout << ++iteration << ": " << input << endl;
        cin.get();
    }
    return 0;
}

So with this code, I can enter anything, but everything after whitespace is somehow like stored in buffer and used in the second iteration.

foo
1: foo
bar
2: bar
foobar
3: foobar
foo bar
4: foo
5: bar

Every single input reading function acts like this and it's driving me crazy. cin >> input, freads(), cin.get() etc. all do this.

It this frequent problem with user input, or am I doing something wrong here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

帥小哥 2024-09-13 10:59:37

首先,永远不要使用 scanf。很难使用该函数并避免缓冲区溢出。将 input 替换为 std::string,并从 std::cin 读取。

scanf("%s", input)cin >> input 将读取一个单词,以空格分隔。如果您想读取整行,请使用getline(cin, input)

First of all, never use scanf. It's difficult to use that function and avoid buffer overflows. Replace input with a std::string, and read from std::cin.

Both scanf("%s", input) and cin >> input will read one word, delimited by whitespace. If you want to read a whole line, then use getline(cin, input).

对你而言 2024-09-13 10:59:37

关于 scanf %s 格式说明符

这将读取后续字符,直到找到空格为止(空格字符被视为空白、换行符和制表符)。

关于 istream::operator>> 与 str参数

当下一个字符是有效的空格或空字符,或者到达文件结尾时,提取结束。

所以是的,这是这些函数的标准行为。

About scanf %s format specifier:

This will read subsequent characters until a whitespace is found (whitespace characters are considered to be blank, newline and tab).

About istream::operator>> with str parameter:

Extraction ends when the next character is either a valid whitespace or a null character, or if the End-Of-File is reached.

So yes, this is standard behaviour for these functions.

小忆控 2024-09-13 10:59:37

也许尝试使用 std::getline 代替?
http://www.cplusplus.com/reference/string/getline/

Maybe try using std::getline instead?
http://www.cplusplus.com/reference/string/getline/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文