Why it works when I type multiple characters in a character variable? - c++

I am a new C++ user.
My code is as following:
#include <iostream>
using namespace std;
int main()
{
int option = 1;
char abstract='a';
while(option == 1){
char temp;
cin>> temp;
abstract = temp;
cout << abstract;
option = 1;
if(abstract == '!'){
option = 0;
}
}
return 0;
}
And when I typed something like: abcdefg
all the characters are on the screen,why? It's just because of the compiler?

In fact, only one character at a time is stored in your char. cin>>temp; reads a single char at a time since more characters would not fit there. The loop simply reads and prints one character after the other.
As a visualization hint, try echoing your characters with cout<<abstract<<endl;. You will see a single character per line/iteration.

Your terminal does not restrict the number of characters typed in , that's why you can type as many as you want. Your c++ compiler would read only one of the characters because 'temp' is of type char. you can type an 'if' statement to check the number of characters typed in the terminal

Because of the while loop, which processes each character in turn. Not sure what you expected to happen.
Print it out with delimiters to see that there's never more than a single character printed per iteration:
cout << "'" << abstract << "'";

The terminal window itself is responsible for reading the characters and echoing them back to the screen. Your C++ program asks the terminal for characters and, in this sort of program at least, has no effect on how those characters are displayed.

Related

Difference between cin and cin.get() for char array

I have these 2 codes:
char a[256];
cin>>a;
cout<<a;
and
char a[256];
cin.get(a,256);cin.get();
cout<<a;
and maybe, relative to the second one without cin.get();
char a[256];
cin.get(a,256);
cout<<a;
My question is (first one) : for a char array, what should i use? cin or cin.get()? And why should i use cin.get(); with no parameter after my char initialisation?
And my second question is: my c++ teacher taught me to use every time cin.get() for initialisation chars and AFTER every initialisation char array or int array or just int or whatever, to again put cin.get(); after it. That's what i wanted to ask initially.
So, now i got these 2:
In this case, without cin.get() after the integer initialisation, my program will break and i can't do anymore my char initialisation.
int n;
cin>>n;
char a[256];
cin.get(a,256); cin.get(); // with or without cin.get();?
cout<<a;
And the correct one:
int n;
cin>>n; cin.get();
char a[256];
cin.get(a,256); cin.get(); // again, with or without?
cout<<a;
So, what's the matter? Please someone explain for every case ! Thank you.
They do different things, so choose whichever does what you want, or the better alternatives given below.
The first cin>>a; reads a single word, skipping over any leading space characters, and stopping when it encounters a space character (which includes the end of the line).
The second cin.get(a,256);cin.get(); reads a whole line, then consumes the end-of-line character so that repeating this will read the next line. cin.getline(a,256) is a slightly neater way to do this.
The third cin.get(a,256) reads a whole line but leaves the end-of-line character in the stream, so that repeating this will give no more input.
In each case, you'll get some kind of ill behaviour if the input word/line is longer than the fixed-size buffer. For that reason, you should usually use a friendlier string type:
std::string a;
std::cin >> a; // single word
std::getline(std::cin, a); // whole line
The string will grow to accommodate any amount of input.
The problem, most likely, is in the way you enter the values later on. The cin.get() after every initialization is there to "grab" the newline character that gets put in the stream every time you press enter.
Say you start entering your values like this:
2
a b c d...
Assuming you have pressed enter after 2, the newline character was also put on the stream. When you call cin.get() after that, it will grab and discard the newline character, allowing the rest of your code to properly get the input.
To answer your first question, for an array, you should use cin.get instead of the overloaded operator >> cin>> as that would only grab a single word, and it would not limit the amount of characters grabbed, which could lead to an overflow and data corruptions / program crashing.
On the other hand, cin.get() allows you to specify the maximum number of characters read, preventing such bugs.
For a char array use cin.get() because it counts whitespace whereas cin does not. More importantly, cin.get() sets the maximum number of characters to read. For example:
char foo[25]; //set maximum number of characters
cout << "Please type in characters for foo" << endl;
cin.get(foo,25);
cout << ' ' << foo;
In this case, you can only type in 24 characters and a null terminator character \0.
I hope this answers your first question.
I would personally use a string.

capitalizing characters, how toupper works?

I need to use a character array and take the characters in the array and capitalize and lower case them as necessary. I was looking at the toupper and its example, but I'm confused about how this works. Looking from the example given on cplusplus.com I wrote
int main(){
int i = 0;
char str[] = "This is a test.";
while(str[i]){
putchar(toupper(str[i]));
i++;
}
for(int i = 0; i < 15; i++){
cout << str[i];
}
}
and there are two things I don't understand about this. The first is that without the cout at the bottom, the program prints out THIS IS A TEST. Does putchar print to the screen? (the use of putchar is not explained on the example). But my second more important question is why does the cout at the bottom still print out This is a test.? Does it not change the chars in str[]? Is there another way I should be doing this (keeping in mind I need to use character arrays)?
Yes, putchar() prints a character to the program's standard output. That is its purpose. It is the source of the uppercase output.
The cout at the bottom of the program prints the original string because you never modified it. The toupper() function doesn't -- indeed can't -- modify its argument. Instead, it returns the uppercased char.
putchar writes a single character to output: http://www.cplusplus.com/reference/cstdio/putchar/
As a result, the first while loop converts each character from str one at a time to upper case and outputs them. HOWEVER, it does not change the contents of str - this explains the lower case output from the second loop.
Edit:
I've expanded the first loop:
// Loop until we've reached the end of the string 'str'
while(str[i]){
// Convert str[i] to upper case, but then store that elsewhere. Do not modify str[i].
char upperChar = toupper(str[i]);
// Output our new character to the screen
putchar(upperChar);
i++;
}

Reading string by char till end of line C/C++ [duplicate]

This question already has answers here:
c++ compile error: ISO C++ forbids comparison between pointer and integer
(5 answers)
Closed 5 years ago.
How to read a string one char at the time, and stop when you reach end of line? I'am using fgetc function to read from file and put chars to array (latter will change array to malloc), but can't figure out how to stop when the end of line is reached
Tried this (c is the variable with char from file):
if(c=="\0")
But it gives error that I cant compare pointer to integer
File looks like (the length of the words are unknown):
one
two
three
So here comes the questions:
1) Can I compare c with \0 as \0 is two symbols (\ and 0) or is it counted as one (same question with \n)
2) Maybe I should use \n ?
3) If suggestions above are wrong what would you suggest (note I must read string one char at the time)
(Note I am pretty new to C++(and programming it self))
You want to use single quotes:
if(c=='\0')
Double quotes (") are for strings, which are sequences of characters. Single quotes (') are for individual characters.
However, the end-of-line is represented by the newline character, which is '\n'.
Note that in both cases, the backslash is not part of the character, but just a way you represent special characters. Using backslashes you can represent various unprintable characters and also characters which would otherwise confuse the compiler.
The answer to your original question
How to read a string one char at the time, and stop when you reach end of line?
is, in C++, very simply, namely: use getline. The link shows a simple example:
#include <iostream>
#include <string>
int main () {
std::string name;
std::cout << "Please, enter your full name: ";
std::getline (std::cin,name);
std::cout << "Hello, " << name << "!\n";
return 0;
}
Do you really want to do this in C? I wouldn't! The thing is, in C, you have to allocate the memory in which to place the characters you read in? How many characters? You don't know ahead of time. If you allocate too few characters, you will have to allocate a new buffer every time to realize you reading more characters than you made room for. If you over-allocate, you are wasting space.
C is a language for low-level programming. If you are new to programming and writing simple applications for reading files line-by-line, just use C++. It does all that memory allocation for you.
Your later questions regarding "\0" and end-of-lines in general were answered by others and do apply to C as well as C++. But if you are using C, please remember that it's not just the end-of-line that matters, but memory allocation as well. And you will have to be careful not to overrun your buffer.
If you are using C function fgetc then you should check a next character whether it is equal to the new line character or to EOF. For example
unsigned int count = 0;
while ( 1 )
{
int c = fgetc( FileStream );
if ( c == EOF || c == '\n' )
{
printF( "The length of the line is %u\n", count );
count = 0;
if ( c == EOF ) break;
}
else
{
++count;
}
}
or maybe it would be better to rewrite the code using do-while loop. For example
unsigned int count = 0;
do
{
int c = fgetc( FileStream );
if ( c == EOF || c == '\n' )
{
printF( "The length of the line is %u\n", count );
count = 0;
}
else
{
++count;
}
} while ( c != EOF );
Of course you need to insert your own processing of read xgaracters. It is only an example how you could use function fgetc to read lines of a file.
But if the program is written in C++ then it would be much better if you would use std::ifstream and std::string classes and function std::getline to read a whole line.
A text file does not have \0 at the end of lines. It has \n. \n is a character, not a string, so it must be enclosed in single quotes
if (c == '\n')

My code is written twice for uncomprehensible reasons

This code is written in C++ and for reasons that I don't quite understand it is written twice.
I would expect that after inputting a random char it would display the char once and the String lower to it once as well. But I don't get this as output. What am I missing?
Solution: Adding a cin.ignore() statement disregards the return that is read in as well.
Making my code go through the loop once.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
char letter;
letter = cin.get();
while (letter!= 'X')
{
cout << letter << endl;
cout << "this will be written twice for ununderstandable reasons";
letter = cin.get();
}
}
Example:
If I were to write in cmd scrn c, I'd get a c back + twice the phrase this will be written twice for ununderstandable reasons. So what I thought to be the output
c
this will be written twice for ununderstandable reasons
is actually
c
this will be written twice for ununderstandable reasons
this will be written twice for ununderstandable reasons
as everyone already mentioned, cin will append the newline marker \n every time you hit enter. another solution is to place cin.ignore(); after every cin.get();.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
char letter;
letter = cin.get();
cin.ignore();
while (letter!= 'X')
{
cout<<letter<<endl;
cout<<"this will be written twice for ununderstandable reasons";
letter= cin.get();
cin.ignore();
}
}
You are reading every character with the unformatted get() function, including the newline character each time you hit return.
Depending on what you're trying to do, you could use formatted input (cin >> c) to skip all whitespace; or you could test each character and ignore things like newline that don't interest you; or you could use getline(cin, some_string) to read a whole line, and then process that.
When you type in a character the new-line character (from pressing enter) is also in your input buffer.
From the C-Reference:
The delimiting character is not extracted from the input sequence if found, and remains there as the next character to be extracted from the stream (see getline for an alternative that does discard the delimiting character).
Just use a cin.sync() after every cin.get() to clear the buffer and you should be good to go.
You forgot about the newline.
cin reads every character, which includes the newline you type after typing your character.
If you don't want this behaviour, you have to specifically check for newline.
while (letter!= 'X')
{
if (letter == '\n')
{
letter = cin.get();
continue;
}
cout<<letter<<endl;
cout<<"this will be written twice for ununderstandable reasons";
letter= cin.get();
}
The text 'this will be written twice..' will not necessarily print twice.
Type 'qwerty' + ENTER and your stream will have "qwerty\n" within and you'll see this output:
this will be written twice for ununderstandable reasons
this will be written twice for ununderstandable reasons
this will be written twice for ununderstandable reasons
this will be written twice for ununderstandable reasons
this will be written twice for ununderstandable reasons
this will be written twice for ununderstandable reasons
this will be written twice for ununderstandable reasons
Exactly that many as string "qwerty\n" has characters.
The problem is that
cin.get()
Puts all chars that you type into a stream/buffer (not your letter char) but handles one char every cin.get() invocation.
When you type 'abcXd' + enter - the program will print above line 3 times and stop on X.
It happens because cin.get() reads new-line character too. Try to press Enter without any symbols or type some string, like abc.
You need to handle it, e.g.:
while (letter = cin.get()) {
if (!isalpha(letter)) { continue; }
// handling user inputted alpha
}

Line Breaks when reading an input file by character in C++

Ok, just to be up front, this IS homework, but it isn't due for another week, and I'm not entirely sure the final details of the assignment. Long story short, without knowing what concepts he'll introduce in class, I decided to take a crack at the assignment, but I've run into a problem. Part of what I need to do for the homework is read individual characters from an input file, and then, given the character's position within its containing word, repeat the character across the screen. The problem I'm having is, the words in the text file are single words, each on a different line in the file. Since I'm not sure we'll get to use <string> for this assignment, I was wondering if there is any way to identify the end of the line without using <string>.
Right now, I'm using a simple ifstream fin; to pull the chars out. I just can't figure out how to get it to recognize the end of one word and the beginning of another. For the sake of including code, the following is all that I've got so far. I was hoping it would display some sort of endl character, but it just prints all the words out run together style.
ifstream fin;
char charIn;
fin.open("Animals.dat");
fin >> charIn;
while(!fin.eof()){
cout << charIn;
fin >> charIn;
}
A few things I forgot to include originally:
I must process each character as it is input (my loop to print it out needs to run before I read in the next char and increase my counter). Also, the length of the words in 'Animals.dat' vary which keeps me from being able to just set a number of iterations. We also haven't covered fin.get() or .getline() so those are off limits as well.
Honestly, I can't imagine this is impossible, but given the restraints, if it is, I'm not too upset. I mostly thought it was a fun problem to sit on for a while.
Why not use an array of chars? You can try it as follow:
#define MAX_WORD_NUM 20
#define MAX_STR_LEN 40 //I think 40 is big enough to hold one word.
char words[MAX_WROD_NUM][MAX_STR_LEN];
Then you can input a word to the words.
cin >> words[i];
The >> operator ignores whitespace, so you'll never get the newline character. You can use c-strings (arrays of characters) even if the <string> class is not allowed:
ifstream fin;
char animal[64];
fin.open("Animals.dat");
while(fin >> animal) {
cout << animal << endl;
}
When reading characters from a c-string (which is what animal is above), the last character is always 0, sometimes represented '\0' or NULL. This is what you check for when iterating over characters in a word. For example:
c = animal[0];
for(int i = 1; c != 0 && i < 64; i++)
{
// do something with c
c = animal[i];
}