简体   繁体   English

从文本文件中读取名称列表到2D数组中

[英]Reading a list of names from a text File into a 2D array

I'm trying to read a column of names from a text file into a two dimensional array, the names vary in length but are at max 8 letters long, and there are 10 of them. 我正在尝试将文本文件中的一列名称读入二维数组,这些名称的长度有所不同,但最长为8个字母,其中有10个字母。 Here are my two for loops to read the names and then to print them. 这是我的两个for循环,用于读取名称然后进行打印。

for (int i = 0; i != 10; i++) {
    for (int j = 0; j != 8; j++) {
        infile >> textfileinfo[i][j];
    }
}

and then to print the names out I have this loop. 然后打印出来的名字,我有这个循环。

for (int i = 0; i != 10; i++) {
    for (int j = 0; j != 8; j++) {
        cout << textfileinfo[i][j];
    }
    cout << " " << endl;
}

Here is the list of names: 这是名称列表:

Victor
Eve
Juliet
Hector
Danielle
Romeo
Oscar
June
Ares
Dannae

What ends up happening is it will read the names out with 8 characters regardless, taking the extra characters from the next name, so Victor turns into VictorEv , then eJulietH and so on. 什么最终发生的是它会读出名字用8个字,无论从下一个名字取多余的字符,所以Victor变成VictorEv ,然后eJulietH等。 How do I get it to start on the next row once the end of Victor is reached, and then move on to Eve etc. I am not allowed to use pointers either. 一旦达到Victor的末端,如何使它从下一行开始,然后继续前进到Eve等。我也不允许使用指针。 Any help is appreciated! 任何帮助表示赞赏! Thanks. 谢谢。

Seems the obvious thing is to use getline . 似乎显而易见的事情是使用getline getline is designed to read a single line of text. getline旨在读取一行文本。

for (int i = 0; i != 10; i++) {
     infile.getline(textfileinfo[i], 9);
}

Note that the second argument to getline is 9 because you need an extra character to store the nul terminator that ends every C style string. 请注意,getline的第二个参数是9,因为您需要一个额外的字符来存储以n个终止符结尾的每个C样式字符串。 This also mean that your 2D array need to be declared with at least 9 characters in each row. 这也意味着您的2D数组必须声明为每行至少包含9个字符。 Slightly safer code would be to make this explicit 稍微更安全的代码将是明确的

infile.getline(textfileinfo[i], sizeof textfileinfo[i]);

If for some reason you aren't allowed to use getline then you going to have to modify your inner loop to detect and deal with the '\\n' character that terminates every line. 如果由于某种原因不允许您使用getline则必须修改内部循环以检测并处理终止每一行的'\\n'字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM