gpt4 book ai didi

c++ - 入门级 hell (p)

转载 作者:行者123 更新时间:2023-11-28 03:42:09 24 4
gpt4 key购买 nike

我在使用这段代码时遇到了一些问题。我正在尝试编写一个函数,允许用户输入一个字符串(多个单词),然后返回第一个单词。 Python 的一个简单任务,但 C++ 再次让我感到困惑。我在途中意识到我仍然需要为第一个 token 添加实现,但在增量调试中我遇到了一些障碍。我要解决的问题是:

  1. 为什么当我输入整数时,函数会在控制台上打印出来?输入整数不应该导致 cin 流失败并因此重新提示用户输入另一个条目吗?
  2. 如何让窗口在返回之前暂停(可能等待用户的“输入”)?它的打印和返回速度如此之快,以至于很难看清它的作用。

代码如下:

/*
* Problem 1: "Extract First String"
* Takes a user string and extracts first token (first token can be a whole word)
*/

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

void ExtractFirstToken();

int main()
{
ExtractFirstToken();
return 0;
}

/*
* Trying to create a function that will allow a user to enter a string of words and
* then return the first word
*/
void ExtractFirstToken()
{
cout << "Please enter a string (can be multiple words): ";
string stringIn;
while (true)
{
cin >> stringIn;
if (!cin.fail()) break;
cin.clear();
cout << "not a string, please try again: ";
}
cout << stringIn;
}

最佳答案

  1. 因为字符串完全可以容纳“12345”。为什么会失败?

  2. 我会说类似 std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
    的内容(呵呵,有趣的是我的回答与本杰明林德利的完全一样,一直到使用 numeric_limits 和 streamsize)

这将等待输入,直到您按下回车。

关于c++ - 入门级 <iostream> hell (p),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8805803/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com