码迷,mamicode.com
首页 > 编程语言 > 详细

C++的学习记录 - 0

时间:2014-12-09 17:15:08      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   sp   for   

最近玩Arduino发现,在编写函数库的时候要用到C++。正好手头有一本教材,于是时隔2年,开始重学。

又看到重载、构造、拷贝这些词竟然还有些小兴奋。

开个系列日志记录一下学习过程中的问题和体会。

 

看到输入输出的时候想到了C++对C的兼容性,于是试了一下printf函数。

 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 }

果然还是不错的。

 

可是又在StackOverFlow上发现了别人的问题。有人在尝试用printf输出string变量。

 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 }

提问者说“Each time the program runs, myString prints a seemingly random string of 3 characters...”

 

对这个问题,直接引用下面chris大神的回答。

It‘s compiling because printf isn‘t type safe, since it uses variable arguments in the C sense. printf has no option for std::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 could happen.

The easiest way to fix this, since you‘re using C++, is printing it normally with std::cout, since std::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 use the c_str() method of std::string to get a const 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_str
11     cin.get();
12 
13     return 0;
14 }

If you want a function that is like printf, 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.

 

复制以上代码,在geany下编译的时候没有成功,提示error: ‘printf’ was not declared in this scope,果然加上#include <stdio.h>后编译成功。

 

由此可见,geany毕竟是一个轻量级的编程环境,main函数必须返回int之类的要求不知道是否是严谨性的体现。总之学习过程中用geany足矣,也希望能借此养成良好的编程习惯。

 

C++的学习记录 - 0

标签:style   blog   http   io   ar   color   os   sp   for   

原文地址:http://www.cnblogs.com/devai/p/4153584.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!