When I first started to learn C ++ code, I encountered a problem, which caused the program to fail to run completely. After reading this article, it will be of great help to you, in addition to studying the basic nature of C ++ code, we will also conduct a comprehensive study on the programming of C ++ code. The following code:
- #include
- int main()
- ...{
- char a,b;
- printf("Please input the first character:");
- scanf("%c", &a);
- printf("Please input the second character:");
- scanf("%c", &b);
- printf("The two characters are %c, %c", a, b);
- return 0;
- }
The program running result is as follows:
The running result is as follows:
- #include
- int main()
- ...{
- char a;
- int b;
- printf("Please input the first character:");
- scanf("%c", &a);
- printf("Please input the second integer:");
- scanf("%d", &b);
- printf("The two characters are %c, %d", a, b);
- return 0;
- }
At that time, I was very confused about this problem and I forgot it for a long time. Yesterday, a student asked a question about the C ++ Operator overloading. The following code indicates the function of the while loop. It seems that there is no difference in the program running after commenting out:
- iostream& operator >> (iostream& is, b& s)
- ...{
- char temp[b::MAX] = ...{0};
- is.get();
- is.get(temp, b::MAX);
- if(strlen(temp)>0)
- ...{
- strncpy(b.str, temp, b::MAX);
- }
- while(is && is.get()!=' ')
- ...{
- continue;
- }
- return is;
- }
Sure enough, when the input string is less than B: MAX, everything is normal. When the input string is greater than B: MAX, after the first string is entered, enter the second string, the program displays the content of b1 and b2, and the content of b2 is the part of the input string that exceeds the length of B: MAX, which indicates that the previous analysis is correct.
Today I think of this problem again. I suddenly think of the problem that two scanf instances in the C ++ language used in the past. Is it because the input buffer is not automatically cleared? When scanf is used for two consecutive characters, enter the first character and press Enter.
The result line break is used as the second character input. scanf does not distinguish between line breaks and common characters. When a character is input and an integer is input, the Type Mismatch occurs, scanf ignores the linefeed and returns the result only after the correct integer is entered !!!
It can be seen that the standard input stream in C ++ has already processed line breaks. It seems that it is necessary to do some work on its own to use the standard input to process special characters in C ++.
- Introduction to C ++
- Summary Notes on learning and exploring C ++ library functions
- Basic Conception and method of C ++ Class Library Design
- Does C ++ really have market value?
- Basic Conception and method of C ++ Class Library Design