• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

C++ question.

imported_vr6

Platinum Member
i am trying to read in a string from a .dat file into a sting into my program.

Here is what the data file contains. "It was a very very sunny day on the fifth day of november"
I have already opened the file and it is called "inFile" and the string is called "string"

so at first i simply did this.

inFile >> string

when i printed the results, i simple got "It"

how do i go about putting that into a loop?

i tried to use EOF but since i am dealing with chars and EOF returns a int, i am not able to use it?

so how do i go about storing the whole sentence into "string"?
 
You most certainly can and should check for EOF. Yes the EOF method returns an integer condition (0 or 1, i.e. false or true); however, the check for EOF is a check against the OBJECT ITSELF. When you do an inFile.eof(), you're checking to see if inFile has more data available.

Why don't you post your actual C++ code for further critique and suggestions on how to accomplish your task. BTW, do you actually need the entire sentence stored into your variable or do you simply need to print out the sentence?

 
i actually need the whole Sentence stored into "string" i'll post what is in my code so far..


int main( int argc, char *argv[])
{

// check command line arguments
if (argc != 2)
{
cerr << "Invalid number of arguments!!!" << endl;
cerr << "The program will now terminate." << endl;
return (-1);
}

// declare and associate stream with file
ifstream inFile( argv[1] );

// Checks for valid file
if ( !inFile.is_open() )
{
cerr << argv[1] << " could not be opened" << endl;
cerr << "The program will now terminate." << endl;
return -2;
}

string text;


inFile >> text;


cout <<"The string in the file is: " << text << endl;


return 0;

}


Th goal of my project is to be able to print out a summary of the sentence, meaning how many words are there, which on was used most often and other various things. This is my first C++ program so i am not too familiar with the syntex. I am still stuck in the C procedural language world right now 🙂

Thanks.
 
which one was used most often
tip: you've probably already figured you'll need an array, list, map, hash or something for storing and counting words, but you might not have thought about these: for matching them you should do a case-insensitive comparison, and you should trim any ending punction from each word, otherwise you'll treat this as 4 words each appearing once:

This, this and this!
 
Ok, when you get to the part where you're doing:

string text;
inFile >> text;

obviously that's where you need to get your program to read more than the first word in your sentence.
You can throw it in a loop very simply by doing something like this:

string text;
while ( ! ( inFile.eof() ) )
{
inFile >> text;
}

There's a problem though w/ the solution above. Each time the statement "inFile >> text" executes, the value of text gets overwritten w/ the most currently read word. Thus, by the time it gets to EOF, text will only contain the last word in your sentence.

Can you propose a way to work around this? (I don't expect you to necessarily be familiar w/ the syntax; however, if you can explain a workable solution, the code for such a solution can be demonstrated).

Note: I don't want to outright give you the answer as it's to your benefit in the long run to think this challenge through.
 
Originally posted by: DaveSimmons
for matching them you should do a case-insensitive comparison, and you should trim any ending punction from each word, otherwise you'll treat this as 4 words each appearing once:
This, this and this!

I kind of doubt (for the purpose of this exercise) that the instructor will provide such challenging test data, although I may be wrong.

*EDIT* I do completely agree w/ you though that a CASE INSENSITIVE comparison should be performed.
 
Here is more details about the project. The instructor already defined a class called "WordCount"
Each WordCount object can store a string and a interger(for keeping track of how many time the word appears).

The goal, or at least how i think the program should work is that to get the strings broken down into a vector of WordCount objects?? and then looping thorught the vector to print out various results as requested by the instructor. The instructor specified that all letters will be lower case 🙂 ..since the whole class is full of noobs.
 
Is there a command/method that could be used to read in a string along with the whitspace?
I am readin through the book and ran upon the "string insert" capability. However the examples only shows predefined strings and not input from file, but it seems that you must know the locations of where u want the string in be inserted?

heres another solution that might work??
using two string variables "text" and "temp", first read in the string using the while loop and store it in "temp", then somehow add the content of "temp" to the end of "text"?? but that would creat a string with no whitespace, which is not what i want?

I can't thionk of anything else other then that, any tips and clues?
 
The istream::getline method lets you read an entire line from a stream (see this link for more details).

If you use that method though, here's a few things to consider:
1) You'll need to break apart the words in each line that you read in to handle the rest of your assignment (i.e. to handle word counts, etc.)
2) The getline method writes data to CHAR *'s, not class string data types.

Going w/ your 2nd idea, where you use 2 STRING OBJECTS (temp and text), sounds like a pretty good solution to me. As you pointed out though, your whitespace characters are removed going this route.

If your test input data will only be comprised of WORDS and BLANK SPACES (i.e. no other WHITESPACE characters except BLANK SPACES), then it's very easy for you to reconstruct your original string.

a) Read in an initial word into text
b) Open up a loop to read in the remaining words (until EOF):
[*] Read in a word into temp
[*] Append a BLANK SPACE to text
[*] Now append the contents of temp
c) End your loop

Once Steps (a) thru (c) have been performed, string object text will contain a reconstructed complete line. Since you're looping through each word, you can easily add in the remaining logic needed to track individual word counts, total word count, etc.

Two hints:
1) Create a 3rd string object called blankSpace and assign it the value of a BLANK SPACE (i.e. " ")
2) To append a string to an existing string, use the += string operator.
Example) text += blankSpace; // Appends the conents of string object blankSpace to the end of string object text
Example) text += temp; // Appends the contents of string object temp to the end of string object text
 
okay, cool at lease i felt like i figured something out. I am gonna give it a try tomorrow morning. Your solution seems to work for me, at least on a logical level. I really appreaciate your help. I will be back on here as soon as i give it a try! Thanks alot!

Kwan1
 
Why don't you just do an fscanf, scan in the whole line, and then use tokens to seperate the words delimited by a space?

Easier imho.
 
ok, i have managed to read in the sentence, but for some reason, the last word in the sentence get read in twice, for example.
This is the sentence in the datafile:
a very angry and pesky antelope ate all of my angelhair pasta i really really really dislike a very pesky antelope

when i do a cout, this is the result
a very angry and pesky antelope ate all of my angelhair pasta i really really really dislike a very pesky antelope antelope

The string has an duplicate of the last word, which would throw off my results. Heres what my code lookes like.

string text;

vector<string>words;

while ( ! ( inFile.eof() ) )
{
inFile >> text;

words.push_back(text);


}

for( int i = 0; i < words.size(); i++)
{
cout << words[1] <<endl;
}
I have decided to use a vector to store each string since upon more reading of the project description, i realized that i do not need to keep the sentence in tact. My goal for right now is to store each sting into a vector of WordCount objects. The WordCount Class was created for me by my instructor, but right now i have no idea how to implement it. However, i am attempting to working on this implemental approach concept, so i will not bother with the WordCount implementation as of right now.
So does anyone know where my flaw is that is making the last word get read in twice?

Thanks again.

To answer to fscanf question, we have not been taught about tokens yet, so i have no idea what it is. This project is suppose to get the class intune with strings in C++.
 
There's only 1 minor syntax error I see in the logic you posted in here; however, I suspect that you have your code written correctly on your end for the blurb you listed in here:

The code:

for( int i = 0; i < words.size(); i++)
{
cout << words[1] <<endl;
}

should really be:

for( int i = 0; i < words.size(); i++)
{
cout << words[i] <<endl;
}

Now... other than that obvious typo/syntax error you posted in here, I don't see anything above that would cause the last word to be printed twice (nor read in twice). With that said, if you could post more of your program, showing the code both BEFORE and AFTER the blurb you listed, that may help isolate the cause of your "last word duplication bug."

*EDIT* BTW, you can also traverse the Vector by using a VECTOR ITERATOR as demonstrated at this link:

vector<string>::iterator wordIterator;
for(wordIterator = words.begin(); wordIterator != words.end(); wordIterator++ )
{
cout << *wordIterator << endl;
}
 
it was actually an i, I only switched it to a 1 because it made half of my post in italics.Here is my program as it appears.

int main( int argc, char *argv[])
{

// check command line arguments
if (argc != 2)
{
cerr << "Invalid number of arguments!!!" << endl;
cerr << "The program will now terminate." << endl;
return (-1);
}

// declare and associate stream with file
ifstream inFile( argv[1] );

// Checks for valid file
if ( !inFile.is_open() )
{
cerr << argv[1] << " could not be opened" << endl;
cerr << "The program will now terminate." << endl;
return (-2);
}

cout << "Processing File: " << argv[1] <<endl;

string text;

vector<string>words;

while ( ! ( inFile.eof() ) )
{
inFile >> text;

words.push_back(text);


}

for( int i = 0; i < words.size(); i++)
{
cout << words <<endl;
}

return(0);

}
 
why would i want to use a iterator, i am not sure on how to use one.? We havn't went over that in class and i don't think the instructor wants us to use it yet.

Thanks
Kwan1.
 
For testing purposes, change this block of code:
while ( ! ( inFile.eof() ) )
{
inFile >> text;
words.push_back(text);
}


as follows:
while ( ! ( inFile.eof() ) )
{
text=""; // empty out text before storing any data to it
inFile >> text;
if (text.length() > 0) words.push_back(text); // only add "text" if data was read in
}

 
Originally posted by: Kwan1
why would i want to use a iterator, i am not sure on how to use one.? We havn't went over that in class and i don't think the instructor wants us to use it yet.

Thanks
Kwan1.

An iterator is another way of traversing a vector. If you haven't covered them yet, disregard the suggestion. 😛
 
Back
Top