I am tweaking an assignment from school. I am not asking for someone to do my homework, just if what I want to do is possible. In the original assignment, the programmer has already entered a character array in the form of a sentence, pre-counted the characters, and assigned the number to size. A function or two take over, do a "sort/search/delete" couts back to the main the new sentence and the number of characters as newSize. Pretty nifty, but I'm not thrilled with the programmer using a predetermined sentence. I would like to incorporate a user's sentence in place of the pre-programmed sentence. This is what I have done to get the user's sentence:
1 2 3 4 5
char userSentence[100] = {'\0'};
cout << "Enter a sentence of less than 99 characters and spaces." << endl;
cin.getline(userSentence, 99, '\n');
cout << "This is your sentence: " << endl;
cout << userSentence << endl;
From here, I'd like a function (?) to pick up userSentence, count the characters and cout to the user/console how many characters their sentence had. That is more impressive. Is that possible? If so, could someone point me in the right direction?
To help you with my level of understanding, I am completing my first semester of C++ in one week. I guess that means I have a crude if not basic understanding of it.
If you just want to get a sentence from the user and count how many chars the sentence contained, using the string class might be the easier way.
1 2 3
string userSentence;
getline( cin, userSentence ); //read a line from the cmdline including spaces
cout << userSentence.size() << "\n";
If you want to avoid using the string class,
1 2 3 4 5 6
int size = 90;
char* sentence;
sentence = newchar[size]; //dynamically allocate memory for sentence on the heap
cin.getline( sentence, size ); //read in a line of size 'size', delimitted by newline char by default
cout << strlen( sentence );//use built in method strlen to calculate the number of chars
//in char array
#include <iostream>
usingnamespace std;
int main()
{
int size = 90;
char* sentence;
sentence = newchar[size];
cin.getline( sentence, size );
int count = 0;
for ( int i = 0; i < size; i++ )
{
//check for null terminator
if ( sentence[i] != '\0' )
count++;
}
cout << "size of string was " << count << "\n";
return 0;
}
The final example is reliant on the fact that cin.getline() null-terminates the character array by placing a '\0' after the final character inserted into the array. This only works on null-terminated strings.
Edit: Spent about 20 min looking for youtube videos while making this post... Zhuge won.