C ++打印出限制字数 [英] C++ print out limit number of words
问题描述
我是C ++的初学者,我不知道该怎么做。
我想写一个包含文本行的代码。例如。 你好stackoverflow是一个很好的网站
I'm beginner to C++ and I wonder how to do this. I want to write a code which take in a text line. E.g. "Hello stackoverflow is a really good site"
从输出我只想打印出前三个字,跳过其余的。
From the output I want only to print out the first three words and skip the rest.
输出我想要的:Hello stackoverflow is
Output I want: "Hello stackoverflow is"
如果是Java,分裂()。至于C ++我真的不知道。它们是什么类似的或是什么是C ++的方法?
If it was Java I would've used the string split(). As for C++ I don't really know. Is their any similar or what is the approach for C++?
推荐答案
但不检测行尾。
The operator >> breaks a stream into words.
But does not detect end of line.
你能做的是读一行然后得到该行的前三个字:
What you can do is read a line then get the first three words from that line:
#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";
}
}
这篇关于C ++打印出限制字数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!