When I run this program, i get a debug assertion failed! error dialog box pop up that says vector subscript out of range. I have looked through my code and don't see what is wrong. Anyway, here is the code I have written. Any advice is appreciated.
P.S. The file inData.txt contains the following six lines:
5
this is a test
foobar
all your base
class
pony along
The output I am getting from this is only the first case:
Case #1: test a is this
#include <fstream>
#include <string>
#include <vector>
usingnamespace std;
int main()
{
ifstream input; //object to read the data from a file
ofstream output; //object to write the results to a file
int numberOfCases; //variable to store the number of cases
char ch; //variable to check for the newline character
string str; //variable to read each string
vector<string> list; //vector object to store the strings
//open the files for I/O
input.open("inData.txt");
output.open("outData.txt");
//read the number of cases
input >> numberOfCases;
//loop structure to read each line
for(int count = 1; count <= numberOfCases; count++)
{
input >> str; //read the first word in the line
list.push_back(str); //insert the first word in the vector
ch = input.peek(); //check if the next character is the newline character
//while end of line is not reached, continue reading the strings in the line
while(ch != '\n')
{
input >> str; //read the next string
list.push_back(str); //insert the next string in the vector
ch = input.peek(); //check if the next character is the newline character
}
//print the results
output << "Case #" << count << ": ";
for(unsignedint index = list.size() - 1; index >= 0; index--)
output << list[index] << " ";
input.get(ch); //read the newline character
list.clear(); //clean out the vector to read the next line
}
//close the files
input.close();
output.close();
return 0;
}
If you use an unsignedint to loop through your vector, you should do it from beginning to end. Otherwise, you're looking for the index to be less than zero, which will never happen!