I have to call in two files, both have 20 letters in them. my program needs to be able to handle up to 50 chars and stop at the blank space.

i need help getting the chars into the array and stopping at blank space

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
	ifstream inFile("student.txt");
	ifstream infile("correct.txt");

	const int questions=50;
	char student[questions];
	char correct[questions];
	int i;
	int count=0;

	for(count=0; count<questions; count++)
	{
		for (i=0; i<questions; i++)
		{
				inFile >> student[i];
				if (inFile)
					count++;
		}
	}
	for (i=0; i<(count-1); i++)
	{
		cout << student[i] << endl;
	}
	inFile.close();
	infile.close();
	return 0;
}

Recommended Answers

All 6 Replies

-this is just my testing program i'll insert into the over all one-

i need help with the for/if loops

Have you learned while loops? Then you could use while(inFile >> student[count]) and increment count in the body of the loop. That way you'll be able to use that count in a subsequent for loop to display your array rather than displaying empty portions at the end. If you haven't learned while loops you can use a for loop but keep track of count separately from the loop counter.

There are a few inconsistencies with your for loops. In the first one, you're incrementing count in the body of the loop as well as in the loop conditions. Your count will reach the amount "questions" twice as fast.

In the last loop, your condition is i<count-1 but this way you will miss the last element of your array as indexing starts at 0 and count-1 will be the last index but as you have it it will stop at count - 2.

well i was also wondering. that program i have compiles, but when it runs it gives me |[ straight down

A compiling program is not necessarily doing what you want at runtime.

I still think the while loop is your best bet as long as that's been covered in the class. Read about all the behind the scenes work that ifstream is doing for you. Then you won't have to worry about the loops since you'll have your count.

yeah we've done while loops. im just not good with infile stuff.... its vertically laid out

It really is as simple as

int count = 0;
while(inFile >> student[i])
       count++;

because each time that loop condition is tested to see whether or not to proceed with the loop, you get a character. When characters are no longer able to be read, the loop halts. Now you have your characters and you have your count!

(Ignore the thing about layout I should have checked it _before_ I posted it, it turns out not to matter)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.