【发布时间】:2014-07-29 06:45:44
【问题描述】:
这是一个更大的代码的一部分,用于逐字读取输入文件,然后以相反的顺序打印单词。它使用一个名为 words[] 的字符串数组来逐字存储程序前面输入文件中的 char 字符串:
//print to screen
for (int i = MAXSIZE; i >= 0; i--)
{
cout << words[i] << " ";
}
测试输入文件内容:
This is my test file. I hope this works.
输出只是“工作”。不断重复。 为什么 i-- 显然从未发生过?
编辑:我的代码中的所有内容。至少可以说,我在这里有点时间紧张。 MAXSIZE=1024 部分实验室提示。不能使用向量或反向;看到这一切,但它是这个实验室的禁区。编程新手,所以如果你能避免居高临下,那就太好了。只是想让这个工作。读取 input.txt 和打印到屏幕位工作正常。输出部分完全失败,我不知道为什么。谁能告诉我为什么而不是侮辱我,谢谢?
//Kristen Korz
//CIS 22A
//This program reads an input file and writes the words in reverse order to an output file.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
//create and link input...
ifstream inputFile;
inputFile.open("input.txt");
//...and output files
ofstream outputFile;
outputFile.open("output.txt");
//error message for file open fail
if (inputFile.fail())
cout << "Error opening the file.\n";
//constant for max size
const int MAXSIZE = 1024;
//string array and temporary-use string
string words[MAXSIZE];
string str; //note: variables will be used for output loops too
//read words from input file
for (int i = 0; (inputFile >> str) && (i < MAXSIZE); ++i)
{
words[i] = str;
//for showing in terminal if read correctly
cout << words[i] << " ";
}
inputFile.close();
cout << endl;
//something wrong with for loop resulting in i apparently not updating
for (int i = MAXSIZE; (outputFile << str) && (i >= 0); --i)
{
words[i] = str;
//for showing in terminal if written correctly
cout << words[i] << " ";
}
outputFile.close();
cout << endl;
system("pause");
return 0;
}
对于带有 i 的输出,我在 for 循环中的 cout 语句说:
cout << words[i] << " " << i << " ";
给终端输出: 这 0 是 1 我的 2 测试 3 文件。 4 我 5 希望 6 这 7 有效。 8 作品。 1023 件作品。 1022 件作品。 1021(大量重复的作品。后面跟着递减的数字)作品。 3作品。 2作品。 1作品。 0
【问题讨论】:
-
什么是
words?words是如何声明的?以及如何将“输入文件”放入words? -
根据@WhozCraig 链接的线程,您似乎正在用输入的最后一个单词“works”填充整个
words数组。 -
@user657267 正是该循环的作用。
标签: c++ for-loop infinite-loop decrement