简体   繁体   English

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

[英]How to only print the first word of a string in c++

How do I set this up to only read the first word the user enters IF they enter to much info?如果用户输入了很多信息,我如何将其设置为仅读取用户输入的第一个单词?

I do not want to use an if-else statement demanding they enter new info because their info was to much.我不想使用 if-else 语句要求他们输入新信息,因为他们的信息太多了。

I just want it to basically ignore everything after the first word and only print the first word entered.我只是想让它基本上忽略第一个单词之后的所有内容,只打印输入的第一个单词。 Is this even possible?这可能吗?

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;

UPDATE更新

It HAS to be a cstring.它必须是一个字符串。 This is something I am working on for school.这是我正在为学校做的事情。 I am asking a series of questions and storing the answers as cstring in the first round.我问了一系列问题,并在第一轮中将答案存储为 cstring。 Then there is a second round where I store them as string.然后是第二轮,我将它们存储为字符串。

try this: 尝试这个:

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;

You need to do: 您需要做:

#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;

If you have to have it less than 10 characters, you can truncate the string as necessary. 如果必须少于10个字符,则可以根据需要截断字符串。 No reason for C-style strings, arrays etc. 没有理由使用C样式的字符串,数组等。

"I have to use ac string." “我必须使用交流弦。” Sigh... 叹...

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;

you could also use this method:你也可以使用这个方法:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM