Wednesday, April 28, 2010

C++: cin & gets

hmmm.. couldn't get cin and gets to work together.
if cin is used before gets, gets will not wait for user input get the string, due to the "\n" character.
if it's the other way round, it will work. but this is not useful in the general sense if your program needs both string and number input.

so in general, use gets and then use "stdlib.h" data conversion functions, eg.: atoi, string -> int

Example:


/*
simple C++ program
*/

#include <iostream>
#include <cstdio>
#include <cstring>
#include <stdlib.h>
using namespace std;

// a c++ program starts with main

int main()
{
int score;
int i;
char str[200];
char c;
c = 'c';

cout << "Enter a number from 1 to 10: " ;
gets_s(str);
score = atoi(str);

cout << "Enter your name: ";
gets_s( str);
for(i = 0; i<score; i++){
cout << c <<"++ is cool and so is " << str << "; score: " << score << "\n";
}
return 0;
}