C++ read file only gives first word [duplicate] - c++

This question already has answers here:
Read whole ASCII file into C++ std::string [duplicate]
(9 answers)
Closed 8 years ago.
I know that I shouldn't use namespace std (using namespace std) as global in this scope, but for this example, I will.
What I ideally want, is to save text to a .txt file and retrieve it. I know that the best option would be fstream and so I decided to use it.
The below code prints out "This". Why does it print out "This" and not the full text?
Here is the code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream fin;
ofstream fout;
string text;
fout.open("C++_text_file_test.txt");
fout << "This is basic text";
fout.close();
fin.open("C++_text_file_test.txt");
fin >> text;
fin.close();
cout << text << endl;
cin.get(); // waits for user to press enter
return 0;
}
I tried researching but didn't quite understand the process of using a loop. Is there an easier way or can someone please explain it?

The >> operator, when used to extract a string, only grabs the characters up to the first white space character. Try using getline to get the whole line.

Related

Writing to a file, compiles, creates a file but doesn't write [duplicate]

This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 7 years ago.
I've read the answers to the "The Questions that may already have your answer" but it didn't help me.
I suppose my problem has a quick solution.
I want to write a program in which
The user inputs the name of the file they want to create.
then
In the same line they input an integer amount=the number of lines of the text of the newly created txt file.
In a new line the user input the first line of the text, in a new line the next line and so on.
And all those lines are saved to the created file.
For example file.txt 3
bhjudshsu 565 jdd
hcxjs
jdckisa jsdjs
And after opening the file named file.txt I should see the above three lines of the text.
Here is my code sample:
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
int amount;
string fileName, line;
ofstream start;
cin>>fileName>>amount;
ofstream out(fileName.c_str());
for(int i=0; i<amount; i++)
{
getline(cin, line);
start<<line<<endl;
}
start.flush();
start.close();
return 0;
}
The problem is that the file is created but it is empty.
Moreover, if I input file.txt 3 the program is closed after I input only two lines.
Could you tell me what I am doing wrong?
You have two ostreams, start and out. You attach out to the file (and write nothing to it), and write to start (which is attached to nothing).
In addition to Beta's answer, cin>> will leave newlines in the buffer when the user presses enter. getline() reads this as the user having pressed enter to "skip" the input.
You can use cin.ignore() to get rid of those extra characters before using getline().
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
int amount;
string fileName, line;
cin >> fileName >> amount;
ofstream start(fileName.c_str());
for(int i = 0; i < amount; i++)
{
cin.ignore();
getline(cin, line);
start << line << endl;
}
start.flush();
start.close();
return 0;
}

What do they mean by "Add these integers to sum"?

Write a simple C++ program called sum.ccp, the program should:
1. Read a file that contains several integers.
2. Print these integers on screen.
3. Add these integers together to sum.
4. Print the sum on the screen.
This is what I have so far:
#include <iostream>
#include <fstream>
#include <string>
int main() {
using namespace std;
ifstream inf("sum.ccp");
while (inf) {
std:: string strInput;
inf >> strInput;
cout << strInput << endl;
}
}
Firstly looking at your code, you're already doing some incorrect things.
int main() {
using namespace std;
ifstream inf("sum.ccp");
while (inf) {
std:: string strInput;
inf >> strInput;
cout << strInput << endl;
}
You need to have using namespace std outside of your main method in order to use the majority of basic C++ commands without tacking on std:: to the beginning. So place it underneath all of the "#include" directives.
Secondly, you should make the variable you're using to take in all of the values an integer, and then simply print the number to the screen with a simple cout command.
The hardest part about your assignment here is just taking the numbers from a text file and using them as integers.
Even then, that's pretty easy. Something like this, using ifstream since you're reading from a file.
ifstream inputFile;
inputFile.open(*your file name here, which should be a .txt file.
I think it works w/ .doc files as well,
but just use a .txt file to be safe.)
After that the process is pretty simple. You do use a while loop, but in this case you use the string insertion operator (the double arrows >>), like so:
while(inputFile >> //your number variable)
This lets the text file keep looping your stuff, while also inserting the value into the variable from the start. So from there you can just print it to the screen, tally up the total, and then after the loop you can print the total the screen.
Hope that helps!

fstream to display all text in txt

I want to display all the text that is in the fille to the output,
I use by using the code below, the code I got up and results posts are just a little out
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
char str[10];
//Creates an instance of ofstream, and opens example.txt
ofstream a_file ( "example.txt" );
// Outputs to example.txt through a_file
a_file<<"This text will now be inside of example.txt";
// Close the file stream explicitly
a_file.close();
//Opens for reading the file
ifstream b_file ( "example.txt" );
//Reads one string from the file
b_file>> str;
//Should output 'this'
cout<< str <<"\n";
cin.get(); // wait for a keypress
// b_file is closed implicitly here
}
The above code simply displays the words "This" does not come out all into output.yang I want is all text in the file appear in the console ..
The overloaded operator>> for char* will only read up to the first whitespace char (it's also extremely risky, if it tries to read a word longer then the buf length you'll end up with undefined behavior).
The following should do what you want in the most simple manner, as long as your compiler supports the rvalue stream overloads (if not you'll have to create a local ostream variable and then use the stream operator):
#include <fstream>
#include <iostream>
int main()
{
std::ofstream("example.txt") << "This text will now be inside of example.txt";
std::cout << std::ifstream("example.txt").rdbuf() << '\n';
}
try something like this
#include <fstream>
#include <iostream>
using namespace std;
int main(){
string line;
ofstream a_file ( "example.txt" );
ifstream myfile ("filename.txt");
if (myfile.is_open()) {
while ( getline (myfile,line) ) {
a_file << line << '\n';
}
myfile.close();
a_file.close();
} else
cout << "Unable to open file";
}
Hope that helps
This is not the best way to read from a file. You probably need to use getline and read line by line. Note that you are using a buffer of fixed size, and you might cause an overflow. Do not do that.
This is an example that is similar to what you wish to achieve, not the best way to do things.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
string str;
ofstream a_file("example.txt");
a_file << "This text will now be inside of example.txt";
a_file.close();
ifstream b_file("example.txt");
getline(b_file, str);
b_file.close();
cout << str << endl;
return 0;
}
This is a duplicate question of:
reading a line from ifstream into a string variable
As you know from text input/output with C++, cin only reads up to a newline or a space. If you want to read a whole line, use std::getline(b_file, str)

File Handling C++ Error

I wanted write a program which allows users to write some random stuff, but i got an
error saying no matching call to which I am not able to figure it out. please Help me.
while you are trying to answer to this question, try to be more noob specific.
here is my code
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
string story;
ofstream theFile;
theFile.open("Random.txt");
while(cin.get(story,5000)!=EOF)
{
theFile<< story;
}
return 0;
}
cin.get with 2 arguments expects char* as first argument and you are trying to pass string as the first argument.
If you want to read std::string instead of C-string until the end of line use getline(cin, story)
If you want to read string until the next space or newline or another blank symbol use cin >> story;
You seem to be trying to write the content of cin to a file. You could just use stream operators:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string story;
ofstream theFile;
theFile.open("Random.txt");
if(cin >> story)
{
theFile << story.substr(0, 5000);
}
return 0;
}
I am assuming that you only want the first 5000 characters in Random.txt...

Reading strings and integers from .txt file and printing output as strings only

I'm new to C++, and I'm trying to write a short C++ program that reads lines of
text from a file, with each line containing one integer key and one alphanumeric string value (no embedded whitespace). The number of lines is not known in advance, (i.e., keep reading lines until end of file is reached). The program needs to use the 'std::map' data structure to store integers and strings read from input (and to associate integers with strings). The program then needs to output string values (but not integer values) to standard output, 1 per line, sorted by integer key values (smallest to largest). So, for example, suppose I have a text file called "data.txt" which contains the following three lines:
10 dog
-50 horse
0 cat
-12 zebra
14 walrus
The output should then be:
horse
zebra
cat
dog
walrus
I've pasted below the progress I've made so far on my C++ program:
#include <fstream>
#include <iostream>
#include <map>
using namespace std;
using std::map;
int main ()
{
string name;
signed int value;
ifstream myfile ("data.txt");
while (! myfile.eof() )
{
getline(myfile,name,'\n');
myfile >> value >> name;
cout << name << endl;
}
return 0;
myfile.close();
}
Unfortunately, this produces the following incorrect output:
horse
cat
zebra
walrus
If anyone has any tips, hints, suggestions, etc. on changes and revisions
I need to make to the program to get it to work as needed, can you please
let me know?
Thanks!
See it:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string name;
int value;
ifstream myfile("text.txt", ifstream::in);
while(myfile >> value >> name)
cout << name << endl;
return 0;
}
You are having problems because you attempt to read each line twice: first with getline and then with operator>>.
You haven't actually used std::map in any regard, at all. You need to insert the integer/string pair into the map, and then iterate over it as the output. And there's no need to close() the stream.
Instead of using "! myfile.eof()" use this code it will help.
ifstream is;
string srg;
is.open(filename);
while(getline(is,srg))
{//your code
}