2013-07-30 96 views
0

好吧,我不得不做一个程序来拆分字符串的元素。之后打印这些文字。 我正面临一些问题: 1)数组打印的字符数大于字符串的大小,我希望一旦打印出最后一个字,它就应该结束打印。我试图阻止它,但当我试图打破最后一个词时,它总是给运行时错误。 2)有没有其他有效的方式来分割和打印?数组大小和字符串拆分

#include <sstream> 
#include <iostream> 
#include<cstdio> 
#include<cstdlib> 
#include <string> 

using namespace std; 

int main() 
{ 
    std::string line; 
    std::getline(cin, line); 
    string arr[1000]; 
    int i = 0; 
    int l=line.length(); 
    stringstream ssin(line); 

    while (ssin.good() && i < l) 
    { 
     ssin >> arr[i]; 
     ++i; 
    } 

    int size = sizeof(arr)/sizeof(arr[0]); 

    for(i = 0; i <size; i++){ 
     cout << arr[i] << endl; 
    } 

    return 0; 
} 
+2

请修复您的代码缩进:) – Borgleader

+0

尝试在(SSIN >>常用3 [我++]); –

+0

固定:)现在好? – rightguy

回答

3
int size = sizeof(arr)/sizeof(arr[0]); 

这是一个编译时的值,它总是将是你的阵列(1000)中元素的个数。它不知道你在循环中分配了多少个字符串。您存储了多少成功读取字符串(加1)在i变量,所以你可以这样做,而不是:

int size = i - 1; 

但是,如果它是对我,我只想用一个可扩展的结构,如向量( #include <vector>

std::vector<std::string> arr; 
std::string temp; 
while (ssin >> temp) 
{ 
    arr.push_back(temp); 
} 

for (auto const & str : arr) 
{ 
    std::cout << str << std::endl; 
} 

/* If you're stuck in the past (can't use C++11) 
    for (std::vector<std::string>::iterator = arr.begin(); i != arr.end(); ++i) 
    { 
     std::cout << *i << std::endl; 
    } 
*/ 

对于通用基于字符分割,我更希望boost::split(我知道你不能使用它,但备查)

std::vector<std::string> arr; 
boost::split(arr, line, boost::is_any_of(".,;!? ")); 
+0

如果我是问题作者,我会将其标记为答案。它非常优雅和详尽 –

1

阅读函数strtok。这是旧派,但非常容易使用。

+1

或更好,'strtok_r()'。太糟糕了,这个答案会因为不使用漂亮的标准库类而被压低和降低。和jQuery。 – 2013-07-30 20:44:46

0

1)有一对夫妇的变化,你应该让你的程序:

#include <sstream> 
    #include <iostream> 
    #include <string> 
    using namespace std; 
    int main() 
    { 
    std::string line("hello string world\n"); 
    string arr[1000]; 
    int i = 0; 
    stringstream ssin(line); 
    while (ssin.good() && i < 1000) 
    { 
     ssin >> arr[i++]; 
    } 
    int size = i-1; 
    for(i = 0; i < size; i++){ 
     cout << i << ": " << arr[i] << endl; 
    } 
    return 0; 
    } 

即,你不希望打印sizeof(arr)/sizeof(arr[0])(即1000)的元素。在条件没有意义i < l

2)stringstream是好的,如果你只是想分开单个字符串;如果需要更多,请使用boost/tokenizer分割字符串。这是现代的C++,一旦你尝试它,你永远不会回来!

+0

对不起,但这些靴子不会在各种编码网站提交的程序中工作:( – rightguy

+0

编辑相应 –

0

这是最好的方法,我认为不用担心,现在

#include <sstream> 
#include <iostream> 
#include<cstdio> 
#include<cstdlib> 
#include <cstring> 
#include <string> 
using namespace std; 
int main() 
{ 
std::string str; 
std::getline(cin, str); 
string arr[100]; 
int l=0,i; 

char * cstr = new char [str.length()+1]; 
std::strcpy (cstr, str.c_str()); 

// cstr now contains a c-string copy of str 

char * p = std::strtok (cstr,".,;!? "); 
while (p!=0) 
{ 
//std::cout << p << '\n'; 
arr[l++]=p; 
p = strtok(NULL,".,;!? "); 
} 
for(i = 0; i <l; i++) 
{ 
    cout << arr[i] << endl; 
} 

delete[] cstr; 
return 0; 
}