如何从一行 C++ 中提取两个字符串

how to extract two strings from a line c++

本文关键字:字符串 提取 两个 一行 C++      更新时间:2023-10-16

假设我必须读取以下输入:

dog ogday
cat atcay
pig igpay
froot ootfray
loops oopslay
str1 str2
atcay
ittenkay
oopslay

所以我无法单独存储所有字符串。 这是我能想出的一部分代码。

while(1)
{
getline(cin,s);
if(s.empty())
break;
else
cout<<s<<endl;
}

所以现在我可以将"dog ogday"存储在一个字符串中。但我想将它们存储在单独的字符串中。请帮忙。(提前致谢:D(

使用cin获取两个字符串:

string a,b;
cin >> a >> b;
int i=0;
while(i<9){
getline(cin,s);
if(s.empty())
break;
else
cout<<s<<endl;
i++;
}

不确定这是否是您想要的,但我认为它会让您存储所有 9 个字符串。

这将分别读取所有"单词"(用空格分隔(。

#include <iostream>
#include <string>
#include <sstream>
int main()
{
for (std::string s; std::getline(std::cin, s) && !(s.empty() || s.find_first_not_of(' ') == std::string::npos); )
{
std::istringstream stream{s};
for (std::string str; stream >> str; std::cout << str << 'n');
}
}