ducky801
asked on
EASY POINTS: Newbie Question. cin only seems to assign the first character entered to the strnig variable
Hi all,
I just started to learn C++ so bare with me. In this program, when it asks me for my name, I enter "Adam", then press enter. I'm expecting the screen to then print "Adam, you're amazing!", but it doesn't. What i see is "A, you're amazing". only the first byte of the string i enter is going into the variable myname. Why? and whats the fix?
I just started to learn C++ so bare with me. In this program, when it asks me for my name, I enter "Adam", then press enter. I'm expecting the screen to then print "Adam, you're amazing!", but it doesn't. What i see is "A, you're amazing". only the first byte of the string i enter is going into the variable myname. Why? and whats the fix?
// Testing.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
char myname;
int _tmain(int argc, _TCHAR* argv[])
{using namespace std;
cout << "Whats your name?\n";
cin >> myname;
cout << "\n";
cout << myname << ", you're amazing!\n";
system("pause");
return 0;
}
The probem is char myname; is only a type for 1 character, try changing it to char myname[100], which will allow for up to 100 chars.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Great! That worked. I knew it would be something small. One more thing before I assign points then:
What if i don't know what the length of my string and i want to allow it to be the maximum that is 'binarily' possible?
AR
What if i don't know what the length of my string and i want to allow it to be the maximum that is 'binarily' possible?
AR
>> What if i don't know what the length of my string and i want to allow it to be the maximum that is 'binarily' possible?
use std::string, see my 2nd post. It'll dynamically grow. You can't dynamically grow a fixed size array (clue is in the name :) )
use std::string, see my 2nd post. It'll dynamically grow. You can't dynamically grow a fixed size array (clue is in the name :) )
ASKER
The program broke on string::myname; I assume its because i'm using the microsoft compiler??
ASKER
Thanks for the help!
>> he program broke on string::myname; I assume its because i'm using the microsoft compiler??
Nope, thats cos I can't type :)
try...
string myname;
I must have accidentally typed :: between the string and the name... sorry :)
Nope, thats cos I can't type :)
try...
string myname;
I must have accidentally typed :: between the string and the name... sorry :)
// Testing.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
string myname;
cout << "Whats your name?\n";
cin >> myname;
cout << "\n";
cout << myname << ", you're amazing!\n";
system("pause");
return 0;
}
ASKER
Success! Thanks again!
No worries... sorry I can't type :)