Wrox Programmer Forums
|
C++ Programming General discussions for the C++ language. For questions specific to Microsoft's Visual C++ variant, see the Visual C++ forum instead.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the C++ Programming section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
  #1 (permalink)  
Old July 21st, 2011, 07:46 PM
Registered User
 
Join Date: Jul 2011
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
Default cin.getline issues

Hello-
I am new to C++ and was am working my way through a book and doing the exercises. One of these exercises was to write a program that will get the user to enter a string and then print it back out. I decided to use the cin.getline iostream function to accomplish this. Here is the pertinent code:
Code:
 char buffer[30];
		cin.getline(buffer, 30, '\n');
		for(int i = 0; i < 30; i++)
			cout << buffer[i];
However, when I compile and run this program, a blank terminal simply flashes on and then disappears into cybernetic oblivion and I never get a chance to enter input. What did I do wrong?
Reply With Quote
  #2 (permalink)  
Old September 19th, 2011, 04:22 PM
MtD MtD is offline
Registered User
 
Join Date: Sep 2011
Posts: 4
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Since you're using C++, try the user-friendly C++ std::string, instead of not-so-user-friendly C-style char array.
So, essentially:
Code:
#include <iostream>
#include <string>
 
int main()
{
  std::string UserEnteredString;
  std::cin >> UserEnteredString;
  std::cout << UserEnteredString << '\n';
 
}
Incidentally, you don't have to print out your C-style char array "buffer" character-by-character, you can simply stream the entire thing via cout: http://www.cplusplus.com/reference/i...tream/getline/
Reply With Quote





Similar Threads
Thread Thread Starter Forum Replies Last Post
cin.getLine() function skips. Please help! unpopular C++ Programming 3 February 29th, 2008 11:50 AM
Problems with cin eye_of_telescope C++ Programming 1 March 17th, 2005 10:41 AM
C++ Beginner having (the usual?) getline problems Slapworth C++ Programming 2 October 10th, 2004 01:45 PM
more getline problmes Gubber C++ Programming 1 July 17th, 2004 06:16 PM
cin.getline alfrepa Visual C++ 0 April 14th, 2004 08:05 PM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.