Hello all,
I have a few questions about C++ (I have programmed quite a bit in VBA and some in the past using C++, and have been working through relearning C++). Currently I am working through a bit on the "Char" variable type.
regarding the following (from the FAQ):
* Don't use system("pause") to pause your program if possible. Use getchar( ) if you are using C and cin.get( ) if you are using C++.
I was using cin.get() to do this recently, but ran into a problem where it no longer worked? See the code below for where it was happening. I am not sure why cin.get() was working before, but as soon as I added a cin of my own, it stopped.
I also am not entirely sure why this is not working as I thought it would, using the following program, I attempted to implement a couple things where it takes a user input char array (I am not sure I did this correctly) and then determines how many numbers/letters are in it. It also does not seem to like using a space as an input (for example if I put "this is a testing string 12345!" as the input, it seems to only get "this" from it).
Now, I have found through some cout-ing that when I create the char array, it fills it with random stuff (so I get incorrect results).
Am I completely missing something regarding the use of the Char here?
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
//define the functions used later
int numbLetters(char inputChar[], int length);
int numbNumbers(char inputChar[], int length);
int main() {
// There is a difference between single and double quotes
// When declaring a character use single quotes
// For strings use double quotes
char userChar[50];
cout << "Input some text to be tested" << endl;
cin >> userChar;
cout << endl << "You gave: " << userChar << endl;
cout << "Number letters: " << numbLetters(userChar, (int)sizeof(userChar)/sizeof(char));
cout << endl << "You gave: " << userChar << endl;
cout << "Number of numbers: " << numbNumbers(userChar, (int)sizeof(userChar)/sizeof(char)) << endl;
//pause (needs two for some reason?) actually I have no idea exactly how this works
cin.get();
cin.get();
system("pause");
return 0;
}
int numbLetters(char inputChar[], int length)
{
int counter = 0;
//loop through entire string to find number of characters
for (int i=0; i<length; i++)
{
if (isalpha(inputChar[i]))
counter++;
}
cout << endl << "str length: " << length << endl;
return counter;
}
int numbNumbers(char inputChar[], int length)
{
int counter = 0;
//loop through entire string to find number of numbers
for (int i=0; i<length; i++)
{
if (isdigit(inputChar[i]))
counter++;
}
return counter;
}
edit - ok while no forum searches helped, it turns out that someone else in the currnet last 5 posts or so was having a similar problem about the char input being cut off by a space and was referenced to here - http://www.cplusplus.com/reference/string/getline/ - but I'm not sure how that relates to the Char array I have above