简体   繁体   English

当ifstream将字符读入2D数组时,出现奇怪的字符

[英]Strange characters follow when ifstream reads characters into 2D array

I'm working on a problem which asks me to read a .txt file containing a word puzzle into a 2D-array of type char and output the words found. 我正在解决一个问题,该问题要求我将包含单词拼图的.txt文件读入char类型的2D数组中并输出找到的单词。 I'm having trouble reading in the puzzle. 我在读拼图时遇到了麻烦。 Here is the code I use now to read in the .txt file and print out the dimensions and the puzzle itself: 这是我现在用来读取.txt文件并打印出尺寸和拼图本身的代码:

ifstream in("puzzle.txt");
string line;
if (in.fail())
{
    cout << "Failed to open puzzle." << endl;
    exit(1);
}

int nrows = 0;
int ncols = 0;
getline(in, line);
ncols = line.size();
++nrows;
while(getline(in, line))
    ++nrows;

in.close();
cout << nrows << ", " << (ncols+1)/2 << endl;

// putting puzzle into a vector of vectors(2D array)
char A[nrows][ncols];
int r = 0;
int c = 0;
char ch;
in.open("puzzle.txt");
while (in >> ch)
{
    A[r][c] = ch;
    if (++c >= ncols)
    {
        c = 0;
        ++r;
    }
}
A[r][c] = 0;

for (int r = 0; r < nrows; ++r)
{
    for (int c = 0; c < ncols; ++c)
        cout << A[r][c] << " ";
    cout << endl;
}

Right now with this code I have, it seems to have read in all the characters at first, but then strange characters follow. 现在我有了这段代码,似乎一开始已经读完所有字符,但随后出现了奇怪的字符。

The result looks like this with an 8x8 puzzle: 结果看起来像是一个8x8拼图:

8, 8 8、8

rdzitpmftekanst rdzitpmftekanst

dtibbarookelahw dtibbarookelahw

aacjiepndksdeoe ac蛇

mzihziylatxishh mzihziylatxishh

eels J ≡ o ` : ≡ o α J ≡ 鳗鱼J≡o`:≡oαJ≡

o ¿ ■ ` V Ω o o¿■`VΩo

   h ²

` α J ≡ o Ç `αJ≡oÇ

  ╢ 5 ╛ s ] 6 @   α J ≡ o

The puzzle ends with "eels". 难题以“鳗鱼”结束。 I did not want the rest. 我不想休息。

Another problem is that besides having strange characters this puzzle also was not printed according to the current dimension, which is only 8 characters per line. 另一个问题是,除了具有奇怪的字符以外,根据当前尺寸(每行仅8个字符),也未打印此拼图。

I have read about solutions involving inserting the null character, but I'm still not quite sure how to do so with a 2D-array of characters. 我已经阅读了有关插入空字符的解决方案的信息,但是我仍然不确定如何使用2D字符数组来实现此目的。

Thanks! 谢谢!

The ncols variable doesn't get the value you want it to have. ncols变量没有获取您想要的值。 Because the line.size() returns the complete size of the array including separator character. 因为line.size()返回包含分隔符的数组的完整大小。 Therefore the double dimensional array is filled with wrong number of columns and some of the last lines are left with the initial random characters. 因此,二维数组被错误的列数填充,并且最后几行保留了初始随机字符。

You're not skipping over the newline characters at the end of each line when you read in each character. 读入每个字符时,您不会跳过每行末尾的换行符。 You can use cin.ignore() to skip it. 您可以使用cin.ignore()跳过它。

for (int r = 0; r < nrows; ++r) {
    for (int c = 0; c < ncols; ++c) {
        cin >> A[r][c];
    }
    cin.ignore();
}

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

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