从行首开始,以空格结束的输入

String Input starting at start of a line and terminates with space

本文关键字:结束 输入 空格 行首 开始      更新时间:2023-10-16

如何在c++中像下面这样接受字符串输入:从行首开始,在第一个空格处结束,忽略该行第一个空格旁边的内容,对于第二个字符串,则转到下一行,输入来自标准输入

的例子:

this is a sample input
here are few lines
looknospaces!

字符串数组应该包含

string[0]=this
string[1]=here
string[2]=looknospaces!

可能一个好的方法是使用getline然后提取每行中的第一个单词,否则我不太喜欢的解决方案是(ab)使用getline分隔符

#include <string>
#include <iostream>
int main()
{
    std::string name, discard;
    std::getline(std::cin, name, ' '); // Takes just the first word (if present)
    std::getline(std::cin, discard); // Takes the rest until n, discard this

,然后你可以加入你想要的