Writing to a file in C++ - c++

I'm trying to make a program that will get the user input of a new file name, create the file, and write to it. It works but it will only write the first word of the string to the file. How can i get it to write the full string? thanks.
#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
for (;;)
{
char *myFile = " ";
string f = " ";
string w = " ";
cout <<"What is the name of the file you would like to write to? " <<endl;
cin >>f;
ofstream myStream(f,ios_base::ate|ios_base::out);
cout <<"What would you like to write to " <<f <<" ? ";
cin >>w;
myStream <<w;
if (myStream.bad())
{
myStream <<"A serious error has occured.";
myStream.close();
break;
}
}
}

According to this post, you should consult this reference to use a method like getline().
Also, when you are writing out I recommend that you flush the output (cout.flush()) before ending the program, especially in this case, since I presume you are ending the program with a ctrl-C break.
In formulating a suggestion, I will read data into char*, and convert them to "string" in case you will use them elsewhere in your program.
I tested this code in MS Visual C++ Express.
#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
for (;;)
{
char *myFile = new char[200]; // modified this line
//added this line
char *myInput = new char[200];
string f = " ";
string w = " ";
cout << "What is the name of the file you would like to write to? " << endl;
cin.getline(myFile, 200);//modified this line
f = (myFile);//added this line
cin.clear(); //added this line
ofstream myStream(f, ios_base::ate | ios_base::out);
cout << "What would you like to write to " << f << " ? ";
cin.getline(myInput, 200);//edited this line
w = string(myInput);//added this line
myStream << w;
myStream.flush();//added this line
if (myStream.bad())
{
myStream << "A serious error has occured.";
myStream.close();
break;
}
delete myFile;
delete myInput;
}
}

You have to use std::getline() to read the entire line:
std::getline(std::cin >> std::ws, w);
The >> std::ws part gets rid of leading whitespace which is needed because the newline left in the stream from the previous extraction will prevent std::getline() from fully consuming the input.
When inserting data into the stream you need to make sure it gets flushed (because, as the other answer said, you're probably using Ctrl+C to terminate the program and you may not see output during the program run). You can use the std::flush manipulator to flush the output:
myStream << w << std::flush;

cin<<w; cin would stop consuming input character when it encounter whitespace tab and other unseeable characters.
you should probably use std::getline() instead.
take a look at this page for ref.
http://en.cppreference.com/w/cpp/string/basic_string/getline
Or you can use manipulator to not skip whitespace.

Related

How to get cin multiple times in different lines?

I want to get input twice with one variable a string and the other character, but it always comes out compilation error, how do I solve this problem. I've tried cin.clear(); but it seems not working in this case.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <string>
using std::string;
using std::getline;
int main(){
string name;
cout << "Please input a string." << endl;
getline (cin, name);
cout << "Hello, there, "<< name <<".\n";
char ccc;
cout << "Please input a character." << endl;
getline (cin, ccc);
cout << "This is a alphabet:" << ccc << endl;
return 0;
}
I expect the output will be like:
Please input a string.
John
Hello, there, John.
Please input a character.
c
This is a alphabet:c
I have used cin.ignore(); before. It should clear the buffer. Also char should use getchar instead of getline.
There is no version of getline() which accepts a char as its second argument. Instead, you probably want the version which accepts a char*. You will need to modify your code to read a string that contains one character.
Try getchar() instead of getline() on the second one.

**Compiler error** - getline() function not accepting first parameter "std:ifstream" what is my issue?

I'm writing a program for my homework that counts words and lines. I'm wondering why i get the error: "no instance of overloaded function "getline" matches the argument list. Argument types are (std::ifstream, int)"
I was certain "infile" was of std::ifstream argument type. Could the problem be visual studio or am i quick to blame something without prior knowledge?
P.S i searched a bit but would not find a thread with exactly the same problem.. there are similar ones but they end up being that someone put a string of the file name and not the stream itself. Also keep in mind i'm in the middle of writing this i didn't finish yet.
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
ifstream infile;
infile.open("Lear.txt");
string word;
int countWords = 0, countLines = 0;
while (!infile.eof())
{
infile >> word;
countWords++;
getline(infile, countLines); //issue area here at infile
countLines++;
}
cout << "Words: " << setw(9) << countWords << endl;
cout << "Lines: " << setw(9) << countLines << endl;
infile.close();
}
There is no std::getline overload that takes an int second parameter. I assume you meant to pass your std::string variable instead.
getline(infile, word);
You should remove the infile >> word; line or decide whether you want to use it or std::getline. I don't think you want both in this case.
This will fix the compiler error but not your program logic. If you use std::getline you'll have to parse each line to count words.

How to print multilple words in c++

I can get the file to save right but I can't seem to get multiple words to write to .txt, like if I type "Hi purple" it just writes "Hi", here is code
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
system("color F0");
string name0;
cout << "Please enter a file name, no spaces/special characters" << endl;
cin >> name0;
name0 = name0+".txt";
system("cls");
cout << " FISHSOFT" << endl;
cout << "The best text editor in the world" << endl << endl;
string text;
cin >> text;
ofstream myfile;
myfile.open (name0.c_str() , ios::out | ios::trunc);
myfile << text;
myfile.close();
system("PAUSE");
return 0;
}
Use std::getline to read an entire line of input including spaces.
cin >> text; will read one whitespace delimited token from the input stream. One word in == one word out.
std::getline(cin, text); will read a whole line. Reading more than that is tricky, but typically a loop around multiple calls to getline.
Suggestion: Save yourself time and fire up your IDE's debugger to see what's happening in your code before posting a question. Almost always faster, and if not, you can make much better, tighter-focused questions.
std::cin is able to get several parameters at once.
That mean you may write:
std::cin >> name0 >> name1 >> name2;
// input: a1 a2 a3
// make: name0: a1, name1: a2, name3:a3
By default, the space is the separator between parameters.
To avoid this behavior, you could use getLine:
std::getline(std::cin, name0);
There are 2 ways to get the string with spaces and special character.
cin.getline(name);
gets(name);
Hope this will serve your purpose.

Printing out blank spaces from a text file in C++

#include <iostream>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <string>
#include <iomanip>
#include <fstream>
#include <stdio.h>
using namespace std;
int main()
{
ifstream file;
string filename;
char character;
int letters[153] = {};
cout << "Enter text file name: ";
cin >> filename;
file.open(filename.c_str());
if (! file.is_open())
{
cout << "Error opening file. Check file name. Exiting program." << endl;
exit(0);
}
while (file.peek() != EOF)
{
file >> character;
if(!file.fail())
{
letters[static_cast<int>(character)]++;
}
}
for (int i = 0; i <= 153; i++)
{
if (letters[i] > 0)
{
cout << static_cast<char>(i) << " " << letters[i] << endl;
}
}
exit(0);
}
#endif
Hi everyone, my current code counts the frequency of each letter from a text file. However, it does not count the number of blank spaces. Is there a simple way to printout the number of blank spaces in a .txt file?
Also, how come when I'm trying to access a vector item, I run into a seg fault?
For example, if I use:
cout << " " + letters[i] << endl;, it displays a segfault. Any ideas?
Thank you so much.
By default, iostreams formatted input extraction operations (those using >>) skip past all whitespace characters to get to the first non-whitespace character. Perhaps surprisingly, this includes the extraction operator for char. In order to consider whitespace characters as characters to be processed as usual, you should alter use the noskipws manipulator before processing:
file << std::noskipws;
Don't forget to set it back on later:
file << std::skipws;
What if you're one of those crazy people who wants to make a function that leaves this aspect (or in even all aspects) of the stream state as it was before it exits? Naturally, C++ provides a discouragingly ugly way to achieve this:
std::ios_base::fmtflags old_fmt = file.flags();
file << std::noskipws;
... // Do your thang
file.flags(old_fmt);
I'm only posting this as an alternative way of doing what you're apparently trying. This uses the same lookup table approach you use in your code, but uses an istreambuf_iterator for slurping unformatted (and unfiltered) raw characters out of the stream buffer directly.
#include <iostream>
#include <fstream>
#include <iterator>
#include <climits>
int main(int argc, char *argv[])
{
if (argc < 2)
return EXIT_FAILURE;
std::ifstream inf(argv[1]);
std::istreambuf_iterator<char> it_inf(inf), it_eof;
unsigned int arr[1 << CHAR_BIT] = {};
std::for_each(it_inf, it_eof,
[&arr](char c){ ++arr[static_cast<unsigned int>(c)];});
for (int i=0;i<sizeof(arr)/sizeof(arr[0]);++i)
{
if (std::isprint(i) && arr[i])
std::cout << static_cast<char>(i) << ':' << arr[i] << std::endl;
}
return 0;
}
Executing this on the very source code file itself, (i.e. the code above) generates the following:
:124
#:4
&:3
':2
(:13
):13
*:1
+:4
,:4
/:1
0:3
1:2
2:1
::13
;:10
<:19
=:2
>:7
A:2
B:1
C:1
E:2
F:1
H:1
I:3
L:1
R:2
T:2
U:1
X:1
[:8
]:8
_:10
a:27
b:1
c:19
d:13
e:20
f:15
g:6
h:5
i:42
l:6
m:6
n:22
o:10
p:1
r:37
s:20
t:34
u:10
v:2
z:2
{:4
}:4
Just a different way to do it, but hopefully it is clear that usually the C++ standard library offers up elegant ways to do what you desire if you dig deep enough to find whats in there. Wishing you good luck.

C++ Processing file freezes program

I am working on a small program that takes a input file and processors the data in the file. With my current code (see below) when you enter a valid file name it just freezes the command line (drops down a line and just shows a flashing _ ) and I have to kill the program to get out. If you enter a invalid file name the if(!file) gets called and runs fine.
Whats really odd is that if I put a debugging cout above that if statement it will not get called if the file name is correct. Hope you can help and if you need more info let me know!
This is my current code:
using namespace std;
#include <iostream>
#include <stdexcept>
#include <string>
#include <fstream>
#include <vector>
#include <cctype>
#include "Student.h"
int main(){
string filename, name;
char *inputfile;
ifstream file;
vector<Student> students;
const int SIZE = 200;
char buffer [SIZE];
int regno, i;
cout << "Enter file name: ";
cin >> filename;
inputfile = const_cast<char*> (filename.c_str());
file.open(inputfile);
if (!file){
cout << "Failed to open " << filename << endl;
exit(1);
}
while (!file.eof()){
file.getline(buffer, SIZE);
i = 0;
regno = 0;
while (isdigit(buffer[i])){
regno = (regno*10)+buffer[i];
}
cout << regno;
}
file.close();
}
Your problems is that you never increase i in the cycle.
Here:
i = 0;
regno = 0;
while (isdigit(buffer[i])){
regno = (regno*10)+buffer[i];
}
You go into infinite cycle as i always stays 0.
Also why do you do the const_cast? You can open using a const char * too. So you can write this:
cin >> filename;
file.open(filename.c_str());
And code will still work.
There's another problem in your code concerning the use of getline() and eof(). The idiomatic way to read a file line-by-line is this:
std::string line;
while(getline(in, line)) {
// handle line here
}
in refers to some input stream like a std::ifstream or std::cin. The point is that reading a line can fail (e.g. due to EOF), which you check in above loop. Your version only checks if EOF was encountered before but not that the subsequent getline() call actually yielded any data.