简体   繁体   English

在C ++中从文件读取2D char数组

[英]Reading a 2D char array from file in C++

First off my knowledge of c++ is very limited this is my first class so this may look dumb but bear with me, i would ask that you please keep it somewhat simple or explain very well thanks in advance. 首先,我对C ++的知识非常有限,这是我的第一堂课,因此,这看起来可能很愚蠢,但请耐心等待,我想请您将其保持简单或预先解释好。

Ok the goal is i want to create this file with the rules inside so that i can read it in in a separate function. 确定的目标是我想使用内部规则创建此文件,以便可以在单独的函数中读取它。 However when i run this i get no errors but it comes out firstly with no spaces at all and i get some random ascii at the end. 但是,当我运行此程序时,我没有出现任何错误,但首先出现的结果是完全没有空格,最后我得到了一些随机的ascii。

here is the results of running the code Welcometothetypinggame1.Typetheentiresentenceinoneline2.IstimedandwillaffectthescoreØ-™wîú{ Dx&a¼ Ë' ©ÉaDx&a®pa 这是运行代码Welcometothetypinggame1.Typeinentilineinoneline2.Istimedand将影响分数Ø-™wîú{Dx&a¼Ë'©ÉaDx&a®pa的结果

#include <cstdlib>
#include <fstream>
#include <iostream>

int main(int argc, char** argv) {
//set the sentences i want the file to print
char o[3][40]={"Welcome to the typing game             ",
            "1. Type the entire sentence in one line",
            "2. Is timed and will affect the score  "};

//creating the file to read in
ofstream out;
out.open("rules.txt");
for(int i=0;i<3;i++){
    for(int x=0; x<39; x++){
        out<<o[i][x];
    }
    out<<"\n";
}
out.close();


//creating a new array to read the data that was stored above
char a[3][40];
ifstream in;
in.open("rules.txt");
for(int i=0;i<3;i++){
    for(int x=0; x<40; x++){
        in>>a[i][x];
    }
}
in.close();

//and just printing out the array to see the results
for(int i=0;i<3;i++){
    for(int x=0; x<40; x++){
        cout<<a[i][x];
    }
}
return 0;
}

The problem lies here: 问题出在这里:

in>>a[i][x];

The extraction operator >> extracts formatted data. 提取运算符>>提取格式化的数据。 Formatted data means that blocks of characters separated by whitespace (like space). 格式化的数据意味着由空格(如空格)分隔的字符块。 During extraction, all whitespace characters are ignored. 提取期间,所有空格字符都将被忽略。 So you can't read whitespace character using >> operator. 因此,您无法使用>>运算符读取空格字符。

What you need to do is to read as unformated data: 您需要做的是读取未格式化的数据:

in.get(a[i][x]);

Read more here and here . 在这里这里阅读更多。

Do not use >> in this particular example. 在此特定示例中,请勿使用>>。 It reads formatted data from your file. 它从文件中读取格式化的数据。 Either use 无论使用

in.get(a[i][x]);

Or even better, drop your char arrays and declare them as strings and put them in a dynamic container, let's say vector. 甚至更好的是,删除您的char数组并将它们声明为字符串,然后将它们放入动态容器中,比如说vector。

ifstream in("rules.txt");
vector<string> myLines;
while (!in.eof()) {
    string temp;
    getline(in,temp);
    myLines.push_back(temp);
}

Now you have all your rules in separate strings stored in a vector. 现在,将所有规则存储在向量中的单独字符串中。 It is also easy to write them to a file. 将它们写入文件也很容易。 When you are iterating with your for loop from 0 to 40, and the string is not 40 characters long, you get your "random ascii". 当您使用for循环从0到40进行迭代,并且字符串的长度不超过40个字符时,您将获得“ random ascii”。

The extraction operator >> will ignore white spaces by default. 默认情况下,提取运算符>>将忽略空格。 You can either read unformated data as suggested in the other answers or you can change the default behavior like this : 您可以按照其他答案中的建议读取未格式化的数据,也可以更改以下默认行为:

in.open("rules.txt");
in >> noskipws;
for(int i=0;i<3;i++){
    for(int x=0; x<40; x++){
        in>>a[i][x];
    }
}

Part 1 第1部分

it comes out firstly with no spaces 首先出来没有空格

the problem is here 问题在这里

for(int x=0; x<39; x++){
   out<<o[i][x];
}

You write only the data, and you do not format your output. 您只写入数据,并且不格式化输出。

You have two possible solutions: 您有两种可能的解决方案:

  1. use <iomanip> and use setw and setfill 使用<iomanip>并使用setwsetfill
  2. add a whitespace after (or before) every entry. 在每个条目之后(或之前)添加一个空格。

Example for the second option: 第二个选项的示例:

for(int x=0; x<39; x++) {
    out << o[i][x] <<" ";
}

Obviously this will put spaces also after the last entry (or before the first). 显然,这还将在最后一个条目之后(或第一个条目之前)放置空格。 Additional code is required if you do not want this. 如果您不希望这样做,则需要附加代码。

Part 2 第2部分

i get some random ascii at the end 我最后得到一些随机的ascii

The problem (as stated by others) lies here: 问题(如其他人所述)在这里:

for(int i=0;i<3;i++){
    for(int x=0; x<39; x++)

You arbitrarily limit/increase your output disregarding the actual size of the variable you have to write/read. 您可以随意限制/增加输出,而不必考虑必须写入/读取的变量的实际大小。

For writing (it is the same for screen or file) you should do something like (please note that this is a solution if o is a vector of vectors, not a char array. I prefer not to use arrays.) 对于编写(对于屏幕或文件来说,是相同的),您应该执行类似的操作(请注意,如果o是向量的向量,而不是char数组,则这是一个解决方案。我不希望使用数组。)

for(int i=0;i<o.size();i++){
    for(int x=0; x<o[0].size(); x++)

For reading, instead, you need to check if you are changing line and/or if you reached the end of the file. 为了阅读,您需要检查是否要更改行和/或是否已到达文件末尾。

如果我没记错的话,每行末尾缺少/ n会阻止“自动换行”,并且全部出现在一行上。

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

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