字符串输入从行的开头开始,以空格结束

时间:2014-03-16 12:11:01

标签: c++

如何在c ++中使用字符串输入,如下所示: 从行首开始,终止于第一个空格,忽略该行第一个空格旁边的内容,第二个字符串进入下一行, 输入来自标准输入

示例:

this is a sample input
here are few lines
looknospaces!

字符串数组应该是conatin

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

1 个答案:

答案 0 :(得分:1)

可能一个好的方法是使用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

然后你可以随意加入他们。