gllwrnce gllwrnce - 2 months ago 6
C++ Question

C++. Doesn't seem to take input from the user

So I'm new to C++. The idea is that it's supposed to give the user two options, and either option reads input from the user. However, neither of them actually reads any input from the user and instead just skips to the end of the program. Any help is really appreciated! Thank you.

(Note: I know it has something to do with the first 'cin' taking in the 'number')

#include <stdio.h>
#define SIZE 80
#include <iostream>
int main(void)
{
FILE * pFile;
int c; // variable to hold character input by user
char sentence[SIZE]; // create char array
char filename[SIZE]; //create filename array
int i = 0; // initialize counter i
int number;
std::cout << "Give a number. 1 for file. Anything else for standard.";
std::cin >> number;
std::cin.clear();



if(number==1)
{

puts("Enter filename to append: ");
while ((i < SIZE-1) && (c = getchar()) != '\n') {
filename[i++] = c;}

filename[i]= '\0';



//fgetc(sentence,80,stdin);
pFile=fopen(filename,"a");
puts("Give a sentence to place in file:");
while ((i < SIZE-1) && (c = getchar()) != '\n') {
sentence[i++] = c;}

sentence[i]= '\0';
fputs(sentence,pFile);
fclose(pFile);

do {
c = fgetc (pFile);

} while (c != EOF);
fclose (pFile);


}
else
{

// prompt user to enter line of text
puts("Enter a line of text:");

// use getchar to read each character
while ((i < SIZE-1) && (c = getchar()) != '\n') {
sentence[i++] = c;}

sentence[i]= '\0';

// terminate string
// use puts to display sentence

puts("\nThe line entered was:");
puts(sentence);
}


}

Answer

I think you must remove character "enter" from stdin. Try:

std::cin >> number;
getchar();