NokkerZZ
NokkerZZ

Reputation: 3

Why std::cin string input asking me for each space

This week I started studing a text files in C++ and in my exercice I have to do a program that the user enter the lines in the file, but... for each space that the user enters, the program asking the new to user.

Here is my code:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main(void){
    ofstream myfile;
    string answer;

    do{
        cout << "Insert a line in the file[END to finalize]: ";
        cin >> answer;
        myfile.open("example.txt");
        myfile << answer;
        myfile.close();
    }while(answer != "END");
}

The result is:

Insert a line in the file[END to finalize]: Hello my friend

Insert a line in the file[END to finalize]: Insert a line in the file[END to finalize]: Insert a line in the file[END to finalize]:

Upvotes: 0

Views: 180

Answers (2)

cHao
cHao

Reputation: 86506

operator>>(istream&, string&) basically grabs the next word. If you want to grab a whole line, try std::getline(std::cin, answer);.

getline won't include the newline, though. Meaning you'll have to do something like myfile << answer << '\n'; to output them as lines.

BTW, in most cases you'd want to either open the file outside the loop, or open it for appending with something like myfile.open("example.txt", ios::app);. Opening the file in the loop each time like you're doing, i'm pretty sure you position the file pointer at the beginning of the file, so each line you write will overwrite at least the first part of the previous line.

Upvotes: 4

Hakan Serce
Hakan Serce

Reputation: 11256

cin >> answer will read one word, delimited by whitespace. If you want to read a whole line, then use getline(cin, answer)

Upvotes: 0

Related Questions