2015-11-14 73 views
2

这是我处理的文本文件的例子:如何将字符串复制到txt文件中?

http://example.com/object1 50 0 
http://example.com/object2 25 1 
http://example.another.com/repo/objects/1 250 0 
ftp://ftpserver.abc.edu:8080 13 5 
... 

我想要的网址,尺寸(第一号)和优先级(第二号)进入阵列。这里是我的代码:

ifstream infile; 
infile.open("ece150-proj2-input.txt"); 

//Get the number of lines in the text file 
int lines = 0; 
while (!infile.eof()) { 
    string line; 
    getline(infile, line); 
    lines++; 
} 

//Get the components in the input file 
char url[lines][50]; 
float size[lines]; 
float delay[lines]; 
for (int i = 0; i < lines; i++) { 
    infile >> url[i] >> size[i] >> delay[i]; 
} 

//Testing if I get the url address correctly 
cout << url[0] << endl; 
cout << url[1] << endl; 

然而,结果是一些奇怪的字符:

pĞQ? 
?Q? 

为什么出现这种情况?任何人都可以解决此问题。谢谢;-)

+1

你已经在while循环之后阅读过EOF,所以没有什么可读的。 – Doorknob

回答

0

这里的问题是,当你读完文件后,现在流是在文件的末尾。您需要拨打infile.seekg(0, infile.beg);才能回到流的开头。您也可以关闭并重新打开infile。

其次,你声明char url[lines][50];你不能这样做。在C++中数组的长度必须是编译时间常量。我真的很惊讶你的代码编译并给你任何输出。

我会建议你使用std :: vector,它就像一个数组,但你可以添加元素到最后。这样你就不需要事先知道行数。

相关问题