Help me about Strings please :(

Hi? I have a problem about like this. It troubles me cause I dont know how to code this really. I dont have an idea like its really empty. please help me :(

Write a program that reads several strings from a file. Display the number of words then display each word as shown in the sample below. Assume that the maximum number of string in the file is 100.

Sample Input (.in):

Smitty
Werbenjagermanjensen.
He
was
number
1!

Sample Output:

Total Number of Words: 6

Word[0] = Smitty
Word[1] = Werbenjagermanjensen.
Word[2] = He
Word[3] = was
Word[4] = number
Word[5] = 1!
Last edited on
I believe you are dealing with fstream's. Here is some sample stuff. Hope it helps:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <fstream>// You have to include this package to allow reading from and to a file.


int main(){

     ifstream in;//This creates an ifstream object named "in". 
//An "ifstream" reads in stuff, and an "ofstream" reads out stuff. 
//They're like any other variable you make, like int x, or double y, etc...

     in.open("filename.txt");// This opens a file you want. 
//If it's saved in the same folder as the codes, you can just call it by name.
// But if it's saved somewhere else, I THINK you have to include the path to that file.

string temp;
while (!in.eof()){//.eof() is a built in function. 
//This statements reads, "while the ifstream in is NOT at the end of the file".

     //So everytime this while loop runs, the program reads in one line from the txt file you opened. 
//In your example above, this while loop will run 6 times.

     in >> temp;//For example, the first run, it reads in the name "smitty". 
//This line of code stores the word "smitty" into the variable name "temp". 
//The second run, it will store the word "werben...." into "temp". 
}
}



THat's a simple way of reading in from a txt file. You should be able to change it a little bit to do what you want.
Last edited on
Topic archived. No new replies allowed.