如何在C++中只打印字符串的第一个单词
How to only print the first word of a string in c++
如果用户输入的信息太多,我该如何设置它只读取用户输入的第一个词?
我不想使用 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。然后是第二轮,我将它们存储为字符串。
试试这个:
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>
std::string word;
std::cout << "Provide a word, up to 10 characters, no spaces.";
std::cin >> word;
std::cout << "The word is: " << word;
如果您必须让它少于 10 个字符,您可以根据需要截断字符串。没有理由 C-style 字符串、数组等
"I have to use a c string." 唉...
char word[11] = {0}; // keep an extra byte for null termination
cin.getline(word, sizeof(word) - 1);
for(auto& c : word)
{
// replace spaces will null
if(c == ' ')
c = 0;
}
cout << "The word is: " << word << endl;
你也可以使用这个方法:
std::string str;
std::cin >> str;
std::string word;
int str_size = str.size();
for(int i = 0; i < str_size; i++){
word.push_back(str[i]);
if(str[i] == ' ') break;
}
std::cout << "\n" << word << std::endl;
如果用户输入的信息太多,我该如何设置它只读取用户输入的第一个词?
我不想使用 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。然后是第二轮,我将它们存储为字符串。
试试这个:
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>
std::string word;
std::cout << "Provide a word, up to 10 characters, no spaces.";
std::cin >> word;
std::cout << "The word is: " << word;
如果您必须让它少于 10 个字符,您可以根据需要截断字符串。没有理由 C-style 字符串、数组等
"I have to use a c string." 唉...
char word[11] = {0}; // keep an extra byte for null termination
cin.getline(word, sizeof(word) - 1);
for(auto& c : word)
{
// replace spaces will null
if(c == ' ')
c = 0;
}
cout << "The word is: " << word << endl;
你也可以使用这个方法:
std::string str;
std::cin >> str;
std::string word;
int str_size = str.size();
for(int i = 0; i < str_size; i++){
word.push_back(str[i]);
if(str[i] == ' ') break;
}
std::cout << "\n" << word << std::endl;