Jump to content
Search In
  • More options...
Find results that contain...
Find results in...
Weber01

Writing file in c++

Recommended Posts

Posted · Original PosterOP

Hi guys,

I have a problem, in a nutshell I would like to create a program in C ++ that reads user input and puts it in a file. I managed to do everything except to write the file,

that is, when the user inserts the text in the file is written only the word that comes before the space, how can I make it print all the text entered by the user?

Link to post
Share on other sites

Without seeing your code we can't really help. But I'm guessing you're using std::cin >> for input which will only read input up to a space character. You can use std::getline to get around that.


1474412270.2748842

Link to post
Share on other sites

What does your current implementation look like?

 

Something like this should do:

#include <iostream>
#include <fstream>
  
int main()
{
  std::ofstream f("file");
  if (f.is_open())
  {
    f << "Some data.\n";
    f.close();
  }
  else
  {
    std::cerr << "Unable to open file." << std::endl;
    return 1;
  }
    
  return 0;
}

 

Link to post
Share on other sites
Posted · Original PosterOP
1 hour ago, fizzlesticks said:

Without seeing your code we can't really help. But I'm guessing you're using std::cin >> for input which will only read input up to a space character. You can use std::getline to get around that.

 

1 hour ago, mshaugh said:

What does your current implementation look like?

 

Something like this should do:


#include <iostream>
#include <fstream>
  
int main()
{
  std::ofstream f("file");
  if (f.is_open())
  {
    f << "Some data.\n";
    f.close();
  }
  else
  {
    std::cerr << "Unable to open file.";
    return 1;
  }
    
  return 0;
}

 

This is my code

#include <iostream>
#include <fstream>
using namespace std;
bool a = false;
int selezione;
string testo,nome;
char ch;

//create file
void crea_file(){
  ofstream myfile;
  cout<<"Inserisci il nome del file (con estensione): ";
  cin>>nome;
  myfile.open (nome);
  myfile.close();
  system("clear");
}
//write file
void scrivi_file(){
  ofstream myfile;
  myfile.open (nome, ios::in);
  cout<<"scrivi il contenuto del file! :\n";
  getline (cin,testo);
  myfile<<testo;
  myfile.close();
  system("clear");

}
//read file
void leggi_file(){
  ifstream myfile;
  myfile.open (nome);
  system("clear");
  cout<<"Il contenuto di "<<nome<<" è\n\n";
    while (!myfile.eof()) {
      myfile.get(ch);
      cout<< ch;
    }
    cout<<"\n\n\n";
  myfile.close();
}

int main (){
do{
  a==false;
  cout<<"Digita 1 per creare un file\n";
  cout<<"Digita 2 per scrivere\n";
  cout<<"Digita 3 per leggere il file\n";
  cin>> selezione;
  system("clear");
  switch (selezione) {
    case 1:
      crea_file();
      break;
    case 2:
      scrivi_file();
      break;

    case 3:
      leggi_file();
      break;

    default:
      a=true;
      break;
  }
}while (a!=true);
cout<<"Arrivederci!";
}

Thanks for your Answer

Link to post
Share on other sites

The error is in your write file method scrivi_file.

 

You are opening a file to write with the in openmode, which is for reading. You want to use out.

int scrivi_file()
{
  std::ofstream myfile;
  
  myfile.open(nome, std::ios::out);
  std::cout << "scrivi il contenuto del file! :\n";
  std::getline(std::cin, testo);
  
  if (myfile.is_open())
  {
    myfile << testo;
    myfile.close();
    std::system("clear");
  }
  else
  {
    std::cerr << "Unable to open file." << std::endl;
    return 1;
  }
  
  return 0;
}

 

Link to post
Share on other sites
Posted · Original PosterOP
5 minutes ago, mshaugh said:

The error is in your write file method scrivi_file.

 

You are opening a file to write with the in openmode, which is for reading. You want to use out.


int scrivi_file()
{
  std::ofstream myfile;
  
  myfile.open(nome, std::ios::out);
  std::cout << "scrivi il contenuto del file! :\n";
  std::getline(std::cin, testo);
  
  if (myfile.is_open())
  {
    myfile << testo;
    myfile.close();
    std::system("clear");
  }
  else
  {
    std::cerr << "Unable to open file." << std::endl;
    return 1;
  }
  
  return 0;
}

 

I do not understand why using the getline method this is bypassed and the program proceeds going forward without inserting the input

Link to post
Share on other sites
16 minutes ago, Weber01 said:

I do not understand why using the getline method this is bypassed and the program proceeds going forward without inserting the input

Why what is bypassed?

Link to post
Share on other sites

This is because there is data left in the input stream after the use of std::cin, which is being picked up by getline.

Link to post
Share on other sites
Posted · Original PosterOP
37 minutes ago, mshaugh said:

This is because there is data left in the input stream after the use of std::cin, which is being picked up by getline.

then?
 

Link to post
Share on other sites
Posted · Original PosterOP
6 minutes ago, fizzlesticks said:

Don't mix input methods. Use getline everywhere.

I tried to put getline also in the first procedure but once you run the code typing "1" does not work either.

As for the switch selection I can not put getline because it's an integer

Link to post
Share on other sites
16 minutes ago, Weber01 said:

As for the switch selection I can not put getline because it's an integer

You can get the input as a string and convert it yourself using the stoi function or using a stringstream to convert it in a way similar to cin.


1474412270.2748842

Link to post
Share on other sites
10 hours ago, Weber01 said:

One of the main problems is that schools and many (older) textbooks teach this stuff wrong.

They (hopefully) teach students to check the result of operations before continuing and handling errors.

However, when it comes to basic console keyboard input they tend to touch upon operator ">>" and then press on, without discussing error handling and whether or not the operation consumes delimiters or not.

 

Operator ">>" does not consume the delimiter, it's still in the stream and the next input operation will return immediately because of it.

getline does consume the delimiter.

Furthermore, both can fail and you should check the stream state after each input operation.

Operator ">>" is particularly prone to failure in this case due to erroneous user input. For example, you ask for a integer and the user enters text.

 

Here's a little example that does proper error checking and flushes the stream after a successful read:

#include <iostream>
#include <string>
#include <limits>

// Completely clears the cin input stream.
void
FlushCin()
{
	std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

// Keeps trying to read a integer from cin until successfull.
int
ReadInt()
{
	// Loop forever, we will return to caller once we have a successfull read. 
	while (1) 
	{
		std::cout << "Enter a integer: ";
		int i;		

		/* Read integer and test stream state afterward. Streams inherit a 
		   operator bool that evaluates to false if the stream state went bad. */
		if (std::cin >> i)
		{
			// Stream state OK, read successfull...
			FlushCin(); // Clear stream because operator ">>" leaves the delimiter in the stream. 
			return i;
		}
		else
		{
			// Stream state bad, read failed...
			std::cout << "Failed to read a valid integer!, ";
			std::cin.clear();	// Clear stream error state...
			FlushCin();	 	// Flush the erroneous data from the stream.
		}
	}
}

int 
main()
{
	int i = ReadInt();
	std::cout << "\nYou entered " << i << "\n";

	return 0;
}

 

Link to post
Share on other sites
19 minutes ago, Unimportant said:

One of the main problems is that schools and many (older) textbooks teach this stuff wrong.

Well, it's not that textbooks are teaching it wrong, but at the time when those books were written, that was an okay approach. Standards and guidelines change, textbooks don't. 

Link to post
Share on other sites
1 minute ago, PeterBocan said:

Well, it's not that textbooks are teaching it wrong, but at the time when those books were written, that was an okay approach. Standards and guidelines change, textbooks don't. 

Failing to handle errors, especially in this case where a user could easily enter text in stead of a integer, and having the program run off a cliff is plain wrong.

It also confuses the students because their program does not behave as they are taught it would.

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Announcements


×