gpt4 book ai didi

c++ - 如何在C++中只打印字符串的第一个单词

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:09:45 25 4
gpt4 key购买 nike

如果用户输入的信息很多,我该如何设置它只读取用户输入的第一个词?

我不想使用 if-else 语句要求他们输入新信息,因为他们的信息太多了。

我只是想让它基本上忽略第一个单词之后的所有内容,只打印输入的第一个单词。这可能吗?

const int SIZEB = 10;
char word[SIZEB];
cout << " Provide a word, up to 10 characters, no spaces. > " << endl;
cin.getline(word, SIZEB);
cout << " The word is: " << word << endl;
cout << endl;

更新

它必须是一个 cstring。这是我正在为学校做的事情。我问了一系列问题,并在第一轮中将答案存储为 cstring。然后是第二轮,我将它们存储为字符串。

最佳答案

试试这个:

const int SIZEB = 10;
char word[SIZEB];
cout << " Provide a word, up to 10 characters, no spaces. > " << endl;
cin.getline(word, SIZEB);

std::string input = word;
std::string firstWord = input.substr(0, input.find(" "));

cout << " The word is: " << firstWord << endl;
cout << endl;

你需要做的:

#include <string>

关于c++ - 如何在C++中只打印字符串的第一个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41992747/

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