我是C++的初学者,我想知道如何做到这一点.我想写一个接受文本行的代码.例如"Hello stackoverflow是一个非常好的网站"
从输出我只想打印前三个单词,跳过其余的.
我想要的输出:"Hello stackoverflow是"
如果是Java,我会使用字符串split().至于C++,我真的不知道.他们的任何类似或C++的方法是什么?
运算符>>将流分解为单词.
但是没有检测到行尾.
您可以做的是读取一行,然后从该行获取前三个单词:
#include <string>
#include <iostream>
#include <sstream>
int main()
{
std::string line;
// Read a line.
// If it succeeds then loop is entered. So this loop will read a file.
while(std::getline(std::cin,line))
{
std::string word1;
std::string word2;
std::string word3;
// Get the first three words from the line.
std::stringstream linestream(line);
linestream >> word1 >> word2 >> word3;
}
// Expanding to show how to use with a normal string:
// In a loop context.
std::string test("Hello stackoverflow is a really good site!");
std::stringstream testStream(test);
for(int loop=0;loop < 3;++loop)
{
std::string word;
testStream >> word;
std::cout << "Got(" << word << ")\n";
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1001 次 |
| 最近记录: |