提问人:berke 提问时间:4/23/2023 最后编辑:berke 更新时间:4/23/2023 访问量:89
如果所有输入具有不同类型的空格字符,我如何将所有输入作为字符串获取?
how can i get all the input as a string if it has different types of white spaces characters?
问:
例如 输入:
有美好的时光 也有糟糕的时期 结束
#include <iostream>
#include <string>
using namespace std;
//there are good times
//and there are bad times
//END
int main()
{
string str;
getline(cin, str);
cout << str;
}
我怎样才能把它弄进去,一旦所有的 charecters,getline 只得到“有美好时光”的部分
答:
0赞
sujoybyte
4/23/2023
#1
虽然这可能不是一个有效的方法,但你可以检查你在 while 循环中输入的每一行,并在它与你的结束字符串 () 匹配时停止,如下所示。"END"
#include <iostream>
#include <string>
using namespace std;
//there are good times
//and there are bad times
//END
int main()
{
string str;
string currentLine;
string endLine = "END";
while (getline(cin >> ws, currentLine))
{
if (currentLine == endLine)
break;
str += currentLine + "\n";
}
cout << str;
return 0;
}
如果你想让它更简洁,你可以把行检查放在 while 循环中
while (getline(cin >> ws, currentLine) && currentLine != endLine)
str += currentLine + "\n";
评论
2赞
Mukundi Eldridge
4/23/2023
使用 std::getline() 函数获取整行输入, 为了确保获得所有类型的空格字符,可以使用 std::ws 操纵器。此操纵器在读取输入之前丢弃任何前导空格字符。下面是一个示例代码片段,演示了这一点: #include < iostream> #include <string> int main() { std::string input; std::getline(std::cin >> std::ws, input); // 读取整行,包括所有空格字符 std::cout << “Input: ” <<输入<< std::endl;返回 0;}
0赞
sujoybyte
4/23/2023
我用 更新了代码,谢谢std::ws
评论
getline
END
getline