我有一个包含以下内容的文件: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 file\n";
}
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,尝试显示wordsArray,根本没有显示,这里是选择代码3:
else if (selection == 3) {
for (int j = 0; j <= 6; ++j) {
cout << wordsArray[j] << endl;
}
答案 0 :(得分:2)
试试这个(我只写了你应该做的改变,所以保持其他代码原样):
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);
希望这有帮助。