C ++ learning records and learning records
Recently, Arduino found that C ++ is used when writing function libraries. I had a textbook on hand, so I started to study again after two years.
It seems a little excited to reload, construct, and copy these words.
Start a series of logs to record the problems and experiences in the learning process.
When I saw the input and output, I thought of C ++'s compatibility with C, so I tried the printf function.
1 # include<iostream> 2 # include<stdio.h> 3 using namespace std; 4 5 int main() 6 { 7 cout<<"C++ iostream"<<endl; 8 printf("C standard io"); 9 10 return 0;11 }
Sure enough.
However, other problems were found on StackOverFlow. Someone is trying to output the string variable with printf.
1 # include <iostream> 2 3 int main() 4 { 5 using namespace std; 6 7 string myString = "Press ENTER to quit program!"; 8 cout << "Come up and C++ me some time." << endl; 9 printf("Follow this command: %s", myString);10 cin.get();11 12 return 0;13 }
The questioner said, "Each time the program runs,myString
Prints a seemingly random string of 3 characters ..."
For this question, we will directly reference the answer from chris.
It's compiling becauseprintf
Isn't type safe, since it uses variable arguments in the C sense.printf
Has no optionstd::string
, Only a C-style string. using something else in place of what it expects definitely won't give you the results you want. it's actually undefined behaviour, so anything at all cocould happen.
The easiest way to fix this, since you're using C ++, is printing it normallystd::cout
, Sincestd::string
Supports that through operator overloading:
std::cout << "Follow this command: " << myString;
If, for some reason, you need to extract the C-style string, you can usec_str()
Methodstd::string
To getconst char *
That is null-terminated. Using your example:
1 #include <iostream> 2 #include <string> 3 4 int main() 5 { 6 using namespace std; 7 8 string myString = "Press ENTER to quit program!"; 9 cout << "Come up and C++ me some time." << endl;10 printf("Follow this command: %s", myString.c_str()); //note the use of c_str11 cin.get();12 13 return 0;14 }
If you want a function that is likeprintf
, But type safe, look into variadic templates (C ++ 11, supported on all major compilers as of MSVC12 ). you can find an example of one here. there's nothing I know of implemented like that in the standard library, but there might be in Boost, specifically boost::format.
Copy the above Code and compile it in geany. The system prompts error: 'printf' was not declared in this scope. The # include <stdio. h> code is successfully added.
It can be seen that geany is a lightweight programming environment after all, and the main function must return int and other requirements without knowing whether it is a manifestation of rigor. In short, it is enough to use geany in the learning process and hope to develop good programming habits.