1、输入输出

1)operator>>

参考:cplusplus.com

Extracts characters from is and stores them in s as a c-string, stopping as soon as either a whitespace character is encountered or (width()-1) characters have been extracted (if width is not zero).

A null character (charT()) is automatically appended to the written sequence.

Internally, the function accesses the input sequence of is by first constructing a sentry with noskipws set to false: this may flush its tied stream and/or discard leading whitespaces (see istream::sentry).

// example on extraction
#include <iostream> // std::cin, std::cout int main () {
char str[10]; std::cout << "Enter a word: ";
std::cin.width (10); // limit width
std::cin >> str;
std::cout << "The first 9 chars of your word are: " << str << '\n'; return 0;
}

2)getline()

参考:cplusplus.com

Extracts characters from is and stores them into str until the delimitation character delim is found.

Note that any content in str before the call is replaced by the newly extracted sequence.

参考:cppreference.com

When used immediately after whitespace-delimited input, e.g. after int n; std::cin >> n;, getline consumes the endline character left on the input stream by operator>>, and returns immediately. A common solution is to ignore all leftover characters on the line of input with cin.ignore(std::numeric_limitsstd::streamsize::max(), '\n'); before switching to line-oriented input.

#include <iostream>
#include <string>
using namespace std; int main()
{
cout << "Please enter an integer: ";
int number;
cin >> number; // put user input in number cout << "What is your name? ";
cin.ignore(); // Don't use getline after cin >> without using ignore!
string name;
getline(cin, name, '\n'); // put user input in name cout << "Thank you, " << name << ". " << endl;
cout << "Your number is " << number << "." << endl; return 0;
}

3)cin.getline()

参考:cplusplus.com

The delimiting character is the newline character ('\n') for the first form, and delim for the second: when found in the input sequence, it is extracted from the input sequence, but discarded and not written to s.

A null character ('\0') is automatically appended to the written sequence if n is greater than zero, even if an empty string is extracted.

参考:cppreference.com

Extracts characters from stream until end of line or the specified delimiter delim.

// istream::getline example
#include <iostream> // std::cin, std::cout int main () {
char name[256], title[256]; std::cout << "Please, enter your name: ";
std::cin.getline (name,256); std::cout << "Please, enter your favourite movie: ";
std::cin.getline (title,256); std::cout << name << "'s favourite movie is " << title; return 0;
}

注意,cin.getline()属于istream流,而getline()属于string流,getline()的第一个参数是cin,两个函数是不一样的;它们也有共同点,即都可以有第3个用于分隔的参数(默认是'\n')。

详细请参考:Tips and tricks for using C++ I/O (input/output)C++中cin、cin.get()、cin.getline()、getline()、gets()等函数的用法

2、基本类型与字符串之间的转换

1)itoa()

参考:cplusplus.com

Converts an integer value to a null-terminated string using the specified base and stores the result in the array given by str parameter.

This function is not defined in ANSI-C and is not part of C++, but is supported by some compilers.

/* itoa example */
#include <stdio.h>
#include <stdlib.h> int main ()
{
int i;
char buffer [33];
printf ("Enter a number: ");
scanf ("%d",&i);
itoa (i,buffer,10);
printf ("decimal: %s\n",buffer);
itoa (i,buffer,16);
printf ("hexadecimal: %s\n",buffer);
itoa (i,buffer,2);
printf ("binary: %s\n",buffer);
return 0;
}

2)atof(), atoi(), atol()

/* atoi example */
#include <stdio.h> /* printf, fgets */
#include <stdlib.h> /* atoi */ int main ()
{
int i;
char buffer[256];
printf ("Enter a number: ");
fgets (buffer, 256, stdin);
i = atoi (buffer);
printf ("The value entered is %d. Its double is %d.\n",i,i*2);
return 0;
}

3)itoa()区别于iota()

// iota example
#include <iostream> // std::cout
#include <numeric> // std::iota int main () {
int numbers[10]; std::iota (numbers,numbers+10,100); std::cout << "numbers:";
for (int& i:numbers) std::cout << ' ' << i;
std::cout << '\n'; return 0;
}

4)strtod(), strtol()

参考:cplusplus.com

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes as many characters as possible that are valid following a syntax that depends on the base parameter, and interprets them as a numerical value. Finally, a pointer to the first character following the integer representation in str is stored in the object pointed by endptr.

/* strtol example */
#include <stdio.h> /* printf */
#include <stdlib.h> /* strtol */ int main ()
{
char szNumbers[] = "2001 60c0c0 -1101110100110100100000 0x6fffff";
char *pEnd;
long int li1, li2, li3, li4;
li1 = strtol (szNumbers,&pEnd,10);
li2 = strtol (pEnd,&pEnd,16);
li3 = strtol (pEnd,&pEnd,2);
li4 = strtol (pEnd,NULL,0);
printf ("The decimal equivalents are: %ld, %ld, %ld and %ld.\n", li1, li2, li3, li4);
return 0;
}

注意,itoa()与strtol()需要一个参数作为转换的基数。

4)sprintf()

参考:cplusplus.com

Composes a string with the same text that would be printed if format was used on printf, but instead of being printed, the content is stored as a C string in the buffer pointed by str.

On success, the total number of characters written is returned. This count does not include the additional null-character automatically appended at the end of the string.

/* sprintf example */
#include <stdio.h> int main ()
{
char buffer [50];
int n, a=5, b=3;
n=sprintf (buffer, "%d plus %d is %d", a, b, a+b);
printf ("[%s] is a string %d chars long\n",buffer,n);
return 0;
}

5)sscanf()

Reads data from s and stores them according to parameter format into the locations given by the additional arguments, as if scanf was used, but reading from s instead of the standard input (stdin).

On success, the function returns the number of items in the argument list successfully filled. This count can match the expected number of items or be less (even zero) in the case of a matching failure.

/* sscanf example */
#include <stdio.h> int main ()
{
char sentence []="Rudolph is 12 years old";
char str [20];
int i; sscanf (sentence,"%s %*s %d",str,&i);
printf ("%s -> %d\n",str,i); return 0;
}

3、分隔字符串

1)strtok()

参考:cppreference.com

Finds the next token in a null-terminated byte string pointed to by str. The separator characters are identified by null-terminated byte string pointed to by delim.

This function is designed to be called multiples times to obtain successive tokens from the same string.

参考:cplusplus.com

This end of the token is automatically replaced by a null-character, and the beginning of the token is returned by the function.

Once the terminating null character of str is found in a call to strtok, all subsequent calls to this function (with a null pointer as the first argument) return a null pointer.

#include <cstring>
#include <iostream> int main()
{
char input[100] = "A bird came down the walk";
char *token = std::strtok(input, " ");
while (token != NULL) {
std::cout << token << '\n';
token = std::strtok(NULL, " ");
}
}

注意,该函数第一次调用时的参数和以后调用的参数是不同的,它可以搭配cin.getline()一起使用。

2)istringstream, ostringstream, stringstream

stringstream同时具有前两者的功能。

假设输入为

数据结构为

先用istringstream处理

再用ostringstream处理

3)string::find()

void split(const string& str, char delimiter, vector<string>& result) {
auto i = 0;
auto pos = str.find(delimiter);
while (pos != string::npos) {
result.push_back(str.substr(i, pos-i));
i = ++pos;
pos = str.find(delimiter, pos); if (pos == string::npos)
result.push_back(str.substr(i, str.length()));
}
}

详细请参考:Split a string using C++C++常见问题: 字符串分割函数 split

注意,istringstream和stringstream可以搭配getline()一起使用。

C++中的输入参考的更多相关文章

  1. Shell脚本中判断输入参数个数的方法投稿:junjie 字体:[增加 减小] 类型:转载

    Shell脚本中判断输入参数个数的方法 投稿:junjie 字体:[增加 减小] 类型:转载   这篇文章主要介绍了Shell脚本中判断输入参数个数的方法,使用内置变量$#即可实现判断输入了多少个参数 ...

  2. python利用Trie(前缀树)实现搜索引擎中关键字输入提示(学习Hash Trie和Double-array Trie)

    python利用Trie(前缀树)实现搜索引擎中关键字输入提示(学习Hash Trie和Double-array Trie) 主要包括两部分内容:(1)利用python中的dict实现Trie:(2) ...

  3. ChemDraw中如何输入化学式分隔点

    ChemDraw最实用的化学结构绘图软件,在绘制化学结构时,离不开给化学结构标记原子名称,有时还需要插入分隔点,本教程以下图给出的化学结构为例,讲解ChemDraw中如何输入化学式分隔点.  化学结构 ...

  4. C#中实现输入汉字获取其拼音(汉字转拼音)的2种方法

    主要介绍了C#中实现输入汉字获取其拼音(汉字转拼音)的2种方法,本文分别给出了使用微软语言包.手动编码实现两种实现方式,需要的朋友可以参考下 本文刚发布时,只写了一个实现方式,使用的是微软的语言包,但 ...

  5. MathType中如何输入正、余弦函数

    MathType是一款强大的数学公式编辑器,正.余弦函数也是中学中非常重要的一节知识点,今天我们介绍一下在MathType中怎么输入正.余弦函数. 具体步骤如下: 步骤一 打开专业的公式编辑软件Mat ...

  6. 控制input标签中只能输入数字以及小数点后两位

    js 代码如下: /* 控制input标签中只能输入数字 和小数点后两位 */ function checkNum(obj) { //检查是否是非数字值 if (isNaN(obj.value)) { ...

  7. 关于Eclipse中校验输入文件名的源代码

    Eclipse中测试文件名的方法. 也没有单独的分操作系统.在Talend时解决一个在文本框中输入名字有Bug的一个问题,这个是Eclipse中解决输入名字,对名字校验的部分源码. public IS ...

  8. textarea中限制输入字符长度

    要在textarea中限制输入字符的长度,比如在twitter中要限制字符为140个,可实现的方法有: 1. <textarea name="A" cols="45 ...

  9. Android中TextView输入字数统计和限制

    在Android开发应用的时候,文本编辑框中最多输入140个字,经常会显示还剩多少字以限制用户输入的字数, EditText content;//定义一个文本输入框 TextView hasnum;/ ...

随机推荐

  1. MIME (Multipurpose Internet Mail Extensions) 是描述消息内容类型的因特网标准

    http://www.alixixi.com/program/a/2010080364045.shtml MIME 消息能包含文本.图像.音频.视频以及其他应用程序专用的数据. 官方的 MIME 信息 ...

  2. MyBatis部分细节归档

    1. xml中如果要使用到特殊的字符,比如> 或者< 等,使用 <![CDATA[<]> 进行包裹,避免解析XML的时候出错. 2. 后续还有内容,待总结.

  3. 关于Google Chrome 浏览器的一些命令及用法

    http://blog.csdn.net/zyz511919766/article/details/7356306 一些Chrome的地址栏命令(这些命令会不停的变动,所有不一定都是好用的) 在Chr ...

  4. WebDriver(Selenium2) 根据新窗口title切换窗口

    http://uniquepig.iteye.com/blog/1559321 在webdriver官方的api中,切换窗口的方法提供的参数是nameOrHandle. 引用 http://uniqu ...

  5. Codeforces Round #369 (Div. 2) C. Coloring Trees (DP)

    C. Coloring Trees time limit per test 2 seconds memory limit per test 256 megabytes input standard i ...

  6. CodeForces 610A Pasha and Stick

    #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> using ...

  7. CSS的三种手段让元素脱离标准本文档流——浮动、绝对定位、固定定位

    1.浮动 浮动是CSS中用到的最多的一个选项,他有三个性质.关于浮动我们要强调一点,永远不是一个东西单独浮动,浮动都是一起浮动,要浮动,大家都浮动. 1.1 浮动元素脱离标准文档流 1.1.1 大概描 ...

  8. lvs(+keepalived)、haproxy(+heartbeat)、nginx 负载均衡的比较分析

    目前使用比较多的就是标题中提到的这两者,其实lvs和haproxy都是实现的负载均衡的作用,keepalived和heartbeat都是提高高可用性的,避免单点故障.那么他们为什么这么搭配,而又有什么 ...

  9. [无关IT]就这样在凌晨写一篇吧~

    由于新浪博客广告实在太嚣张,自己也都是转载,故决定搬家至此,一改只转不写的习惯T^T,争取记录一下自己的小成长~日后有时间把脑子里的小东西一点点写出来~(好可怕的说)... 好了,睡了!各位爷早睡~ ...

  10. LPC2478的外部中断使用

    LPC2478外部中断 2478的外部中断模型如下 也就是说,port0和2支持外部中断,EINT0-2是三个独立管脚的中断,而EINT3则是port0和2的所有中断共同拥有的向量 对于port0和2 ...