2011-10-02 43 views
0

在C++中,如何将文件内容读入字符串数组?我需要这个对于由对用空格分隔字符的如下文件:将filecontent对的字符读入数组

cc cc cc cc cc cc 
cc cc cc cc cc cc 
cc cc cc cc cc cc 
cc cc cc cc cc cc 

C可以被任何字符,包括空间!尝试:

ifstream myfile("myfile.txt"); 
int numPairs = 24; 
string myarray[numPairs]; 

for(int i = 0; i < numPairs; i++) { 
    char read; 
    string store = ""; 

    myfile >> read; 
    store += read; 

    myfile >> read; 
    store += read; 

    myfile >> read; 

    myarray[i] = store; 
} 

问题是,这只是跳过空格alltogether,因此导致错误的值。我需要改变什么以使其识别空间?

回答

2

这是预期的行为,因为operator>>默认情况下会跳过空格。

解决方案是使用get方法,该方法是一种低级操作,可从流中读取原始字节而不进行任何格式化。

char read; 
if(myfile.get(read)) // add some safety while we're at it 
    store += read; 

顺便说一下,在C++中,VLAs(具有非常量大小的数组)是非标准的。您应该指定一个常量大小,或者使用容器,如vector

1

如果输入的是精确的像你说下面的代码将工作:

ifstream myfile("myfile.txt"); 
int numPairs = 24; 
string myarray[numPairs]; 

EDIT: if the input is from STDIN 
for(int i = 0; i < numPairs; i++) { 
    myarray[i] = ""; 
    myarray[i] += getchar(); 
    myarray[i]+= getchar(); 
    getchar(); // the space or end of line 

} 

EDIT: If we don't now the number of pairs beforehand 
     we shoud use a resizable data structure, e.g. vector<string> 
vector<string> list; 
// read from file stream 
while (!myfile.eof()) { 
    string temp = ""; 
    temp += myfile.get(); 
    temp += myfile.get(); 
    list.push_back(temp); 
    myfile.get(); 
} 
+0

大。现在,如果我事先不知道对的数量呢? – Ben

+0

谢谢你的回答,最后一个问题:你使用矢量的方式,它会一直调整大小,不是吗?我最终将使用的文件包含的内容比我用于该示例的24对还多,因此在读取对之前是否有自动确定所需大小的方法? (另外,我在程序中需要的是文件中“列”和“行”的数量 - 我想我可以使用与myfile.get()相关的列的计数器,并使用手动检查\ n对于rowcounter - 但是在读对之前,事先如何?) – Ben

+0

永远不要在'eof'上循环。只需测试流本身:'while(myfile)'。 –