2017-01-02 64 views
-1

如果您在回答中编写代码,请将其写入,就好像您使用的是namespace std ;.否则,它是我很难阅读:)如何从文本文件的每一行输入N个字符到字符串?

#include <iostream> 
#include <fstream> 
#include <string> 
using namespace std; 

int a; // a is amount of lines in file 
string word[100]; 

int main() 
{ 
    ifstream fd("file.txt"); 
    fd >> a; 
    for(int i=0; i<a; i++) 
    { 
     //here goes the code which inputs, let's say, 20 first characters of a line into string array - word[i]. 
    } 
    fd.close(); 

    return 0; 
} 
+0

什么'的fd <<了'为?? – Raindrop7

+0

FD >> A;将显示文本文件中有多少行,这样我就知道我的for循环需要循环多少次 –

+0

,所以你存储了t他想要读取的文件内的行数? – Raindrop7

回答

1

我会考虑到该文件可能有超过100行(然后可能超过您word - 阵列,并且我还考虑到,该文件可能是不一致的关于a规定的行数和行的实际数量鉴于这种情况,请尝试以下操作:

string line; 
int i; 
for(i=0; getline(fd, line) && i<a && i < 100; i++) { 
    word[i] = line.substr(0,20); 
} 
// at this point, "i" will hold the number of items actually written to "word". 
+0

谢谢你的回应!我并不真正在意100多条线,因为练习非常具体,我正在为我的编程考试做准备(我试图解决前几年的练习题)。但你知道的越多,它越好! –

相关问题