C/C++输入
scanf
scanf("%d", &val)
,需要传入地址,输入换行可以结束输入,它的分隔符是空格、tab或者换行,#include<iostream> #include <string> #include <stdio.h> using namespace std; void scanf_test() { char s[10]; scanf("%s", &s); cout << s << endl; } int main() { scanf_test(); return 0; }
上面的程序中,如果输入的字符串中间有空格,则会直接截断,只读取前面的部分,结果如下图
getchar读取字符
getchar读取所有输入的字符,不会跳过空格等特殊字符
void getchar_test() { char a[6]; for(int i=0;i<5;i++) { a[i] = getchar(); } a[5] = '\0'; cout << a << endl; }
结果如下图
cin
- cin也是按照空格、tab或者换行来分割输入的
- 如果希望输入的字符串中能够包括空格的话,需要使用get或者getline,指定输入字符串的最大长度
注意:使用get,在输入的字符串长度超过设定值时,会将剩余的部分放在缓冲区里,用于下次读取,不会报出异常;使用getline时,输入的字符串长度超过设定值时,cin会报出异常并直接退出读取,但是上一次读取的内容仍然在
参考链接:http://www.cnblogs.com/A-Song/archive/2012/01/29/2331204.html
代码
void cin_test() { cout << "cin.get test" << endl; char s4[10]; char s5[10]; cin.get( s4, 10 ); cin.get( s5, 10 ); cout << s4 << endl; cout << s5 << endl; cout << "cin test" << endl; string s1, s2; cin >> s1 >> s2; cout << s1 << endl; cout << s2 << endl; cout << "cin.getline test" << endl; char s[10]; char s3[10]; cin.getline( s, 10 ); cin.getline(s3, 10); cout << s << endl; cout << s3 << endl; }
上面代码段的运行结果为
文本输入
如果输入内容是存在文本文件中,则可以读取文件,对于一个内容为
5 A + - + - - + - - + - + + + - + - + - + B + - + -
的文本文件,使用下面的方法读取,可以实现文本信息提取。
#include <stdio.h> #include <string.h> int n; char map[100][100]; int main() { freopen("in.txt", "r", stdin); scanf("%d", &n); getchar(); for (int i = 0; i<n; i++) { for (int j = 0; j <n; j++) { scanf("%c", &map[i][j]); getchar(); } } for(int i=0;i<n;i++) { for(int j=0;j<=n;j++) printf("%c", map[i][j]); printf("\n"); } return 0; }
注意:文本中,每两个字符之间有空格,否则在scanf读取的时候会有信息丢失的情况。