The method of reading the character string

1. Read string

Header file should contain: iostream (iostream contains the string).

#include <iostream>

method:

1. read space, tab, carriage return in any one of the end: Direct cin.

string a;
cin >> a;

2. Read a line: getline.

string a;
getline(cin,a);

2. compatible (can read string, you can also read an array of characters)

Need to include the header file: cstdio or stdio.h.

#include <cstdio>

or

#include <stdio.h>

Methods: getchar reads a character, then the order of the characters makes up a string.

string version :( need to report a header file string, the code is as follows:

#include <string>

)

string a;
char b;
while((b=getchar())!='\n'){
    a.pushback(b);
}

Character array version:

char a[],b;
for(int i=0;(b=getchar())!='\n';i++){
    a[i]=b;
}

3. read into an array of characters:

File must contain: cstdio (can not be stdio.h), cstring or string.h

#include <cstdio>
#include <cstring>

or

#include <cstdio>
#include <string.h>

Methods: gets.

char a[];
gets(a);

Guess you like

Origin www.cnblogs.com/eason66-blog/p/in_string.html