2013-05-31 66 views
3

如果我在std::string变量中存储了两个表,我怎么能并排显示它们?尤其是...在C++中用换行符分割字符串

我有std::string table1其中包含以下内容:

X | Y 
------- 
2 | 3 
1 | 3 
5 | 2 

我有std::string table2其中包含以下内容:

X | Y 
------- 
1 | 6 
1 | 1 
2 | 1 
3 | 5 
2 | 3 

我需要对其进行修改(或者真的只是打印出来到标准输出),出现以下内容:

X | Y X | Y 
------- ------- 
2 | 3 1 | 6 
1 | 3 1 | 1 
5 | 2 2 | 1 
      3 | 5 
      2 | 3 

换句话说,我有两个表,存储在std::string变量中,用换行符分隔行。

我想将它们打印到屏幕上(使用std::cout),以便表格并排排列,在顶部垂直对齐。我怎么能这样做?

例如,如果我可以做类似std::cout << table1.nextToken('\n')其中nextToken('\n')给出了一个令牌和令牌是由'\n'字符分隔,然后我可以通过所有令牌制定循环的方法,一旦所有的table1令牌那么我可以简单地打印空格字符,以便table2的剩余令牌正确地水平对齐。但是,这样一个nextToken(std::string)函数并不存在---至少我不知道它。

+1

见[本QA](http://stackoverflow.com/q/236129/485561)和[Boost.StringAlgo](HTTP ://www.boost.org/doc/libs/release/doc/html/string_algo.html)。 – Mankarse

+0

太好了,谢谢:) – synaptik

回答

5

关键词:istringstream,函数getline

Implementaion:

#include <iostream> 
#include <sstream> 
int main() 
{ 
    std::string table1 = 
     " X | Y\n" 
     "-------\n" 
     " 2 | 3\n" 
     " 1 | 3\n" 
     " 5 | 2\n"; 
    std::string table2 = 
     " X | Y\n" 
     "-------\n" 
     " 1 | 6\n" 
     " 1 | 1\n" 
     " 2 | 1\n" 
     " 3 | 5\n" 
     " 2 | 3\n"; 

    std::istringstream streamTable1(table1); 
    std::istringstream streamTable2(table2); 
    while (!streamTable1.eof() || !streamTable2.eof()) 
    { 
     std::string s1; 
     getline(streamTable1, s1); 
     while (s1.size() < 9) 
      s1 += " "; 
     std::string s2; 
     getline(streamTable2, s2); 
     std::cout << s1 << s2 << std::endl; 
    } 
} 
+1

而不是增加空间到S1,尝试'std :: cout << std :: left << std :: setw(9)<< s1 << s2 << std :: endl;' 。需要''iomanip'头文件。 – Bee