2009-11-14 42 views
1

我是C++的初学者,我想知道如何做到这一点。 我想写一个代码,其中包含一个文本行。例如。 “你好,stackoverflow是一个非常好的网站”C++打印出限制字数

从输出我只打印出前三个字,并跳过其余的。

输出我想:“你好计算器是”

如果是Java的我会一直使用的字符串分割()。至于C++,我并不知道。他们有什么相似或C++的方法是什么?

+0

你可能想看看这个[http://stackoverflow.com/questions/53849/how-do-i-tokenize-a-string-in-c],这[http://stackoverflow.com/questions/236129/c-how-to-拆分字符串]和其他[http://stackoverflow.com/questions/275404/splitting-string-c]问题。 – JohnIdol

回答

7

运算符>>将流分解为单词。
但不检测行结束。

你可以做的是读取行然后得到该行的第三个字:

#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"; 
    } 

} 
0

给你一些指点作进一步调查:

对于一个真正的C++解决方案,您可能要查找streamstreaming operators>>CPP Reference是一个很好的在线API参考。

仍然有效的C++,但根源于它的C历史将是strtok()函数标记字符串,它有几个潜在的问题。正如马丁正确指出的那样,它修改了源数据,这并不总是可行的。此外,还存在线程安全和/或重入问题。

所以通常你会更好,使用流和C++字符串。

+0

流迭代器对于这种情况是一种矫枉过正。不幸的是,strtok()修改了底层数据,这不是一件好事。 –

+0

嘿,谢谢,你当然是对的。其实我不知道,为什么我写了'迭代器'...我确信我在考虑运算符:-) – Steffen

0

这是容易的,100%可靠的

void Split(std::string script) 
{ 

    std::string singelcommand; 
    std::stringstream foostream(script); 

    while(std::getline(foostream,singelcommand)) 
    show_remote_processes(_ssh_session,singelcommand); 

}