c++将.txt文件中的字符串添加到字符串数组中,并显示数组的值

c++ add string from .txt file into string array and display the value of the array

本文关键字:数组 字符串 显示 txt c++ 添加 文件      更新时间:2023-10-16

我有一个包含以下内容的文件:tdogicatzhpigu和另一个包含下列内容的文件

dog
pig
cat
rat
fox
cow

在单独的线路上。

下面的代码显示了我在一个do-while循环菜单中执行此操作的尝试。

if (selection == 1) {
        //Gets the characters from the textfile and creates an array of characters.
        fstream fin1("text1.txt", fstream::in);
        if (fin1.is_open())
        {
            cout << "text1.txt successfully added to an array" << endl;
            while (!fin1.eof()) {
                if (!fin1.eof()) {
                    for (int i = 0; i < 14; i++) {
                        for (int e = 0; e < 14; e++) {
                            fin1 >> chArray[i][e];
                        }
                    }
                }
            }
        }
        else if (!fin1.is_open())
        {
            cout << "ERROR: ";
            cout << "Can't open text1.txt filen";
        }
        fin1.close();
        //Get the string values from the file and add into an array of strings
        fstream fin2("search1.txt", fstream::in);
        if (fin2.is_open()) {
            cout << "Search1.txt successfully added to an array" << endl;
            cout << "------------------------------------------------------------------------" << endl;
            while (!fin2.eof()) {
                if (!fin2.eof()) {
                    for (int j = 0; j <= 6; ++j) {
                        getline(fin2, wordsArray[j]);
                    }
                }
            }
        }

现在,如果我打印选择1中的数组,它会正确显示两者,一切都很好,但是在下面的选择2中,我试图再次显示chArray的内容,但由于某种原因,它错过了"t"

else if (selection == 2) {
        for (int i = 0; i < 14; i++) {
            cout << chArray[0][i] << endl;
        }

选择3,尝试显示单词数组,什么都不显示,这是选择3的代码:

else if (selection == 3) {
        for (int j = 0; j <= 6; ++j) {
            cout << wordsArray[j] << endl;
        }

试试这个(我只写了你应该做的更改,所以保持其他代码原样):

string chArray;
string wordsArray[6];
do
{
....//other code
if (selection == 1)
{
   if (fin1.is_open())
   {
      cout << "text1.txt successfully added to an array" << endl;
      if(!getline(fin1,chArray))//read the whole line from the file into the string
         //show error message that a file was not read successfully
   }
   .....
   for (int j = 0; j < 6; ++j)//change j<=6 to j<6 since your array has 6 elements
   .....
}
else if (selection == 2)
{
    for (int i = 0; i < 14; i++)
       cout << chArray[i] << endl;//no need to access this as two dimensional array
.....
}
else if (selection == 3) 
{
    for (int j = 0; j < 6; ++j)//change j<=6 to j<6 since your array has 6 elements
      ....
}
}while(selection != your exit value);

希望这能有所帮助。