2 Replies - 1754 Views - Last Post: 08 October 2012 - 07:57 AM Rate Topic: -----

#1 devonrevenge  Icon User is offline

  • New D.I.C Head

Reputation: -10
  • View blog
  • Posts: 22
  • Joined: 08-October 12

why does getline delete the first word of my string? does c++ hate me?

Posted 08 October 2012 - 05:01 AM

why the hell does getline get the line barring the first word? i tried bodging the problem by trying to pop another word in before it but it just uses that word and then...deletes the first word of the line, i know cin only applies to the first word but thats why i was using getline in the first place...cin on its own gets me just the first word...GRAAAAH *crushes polystyrene coffee cup, slaps wife*



#include <iostream>
#include <string>
#include <fstream>

using namespace std;

main ()
{
string empty = "empty";
string line;
string filename;



cout << "enter file name\n";
cin >> filename;
cin >> line;
ofstream myfile;
myfile.open  (filename.c_str());


getline (cin,line);



myfile << line;


return 0;
}



Is This A Good Question/Topic? 0
  • +

Replies To: why does getline delete the first word of my string? does c++ hate me?

#2 aresh  Icon User is offline

  • It's a 16-Bit World!
  • member icon

Reputation: 273
  • View blog
  • Posts: 4,176
  • Joined: 08-January 12

Re: why does getline delete the first word of my string? does c++ hate me?

Posted 08 October 2012 - 05:42 AM

Yes, C++ hates you for beating your wife :P


Also, you first input a word in "line" on line 17 using cin, then overwrite it by calling getline, with "line" as the string. So, the first word is stored in "line", then overwritten by getline, and hence you don't see the first word. So, remove the extra cin on line 17.

Also, instead of main(), write main() and return 0. In C++, there is no default return type for functions.

This post has been edited by aresh: 08 October 2012 - 05:43 AM

Was This Post Helpful? 1
  • +
  • -

#3 vividexstance  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 678
  • View blog
  • Posts: 2,331
  • Joined: 31-December 10

Re: why does getline delete the first word of my string? does c++ hate me?

Posted 08 October 2012 - 07:57 AM

You should also always check to make sure that the file opened correctly before attempting to write to it.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1