一、从文件中读取字符串
即是getline的用法。
1、在中的getline()函数有两种重载形式
stream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );
2、 在中的getline函数有四种重载形式
用法和上第一种类似,但是读取的istream是作为参数is传进函数的。读取的字符串保存在string类型的str中。
istream& getline (istream& is, string& str, char delim);
istream& getline (istream&& is, string& str, char delim);
istream& getline (istream& is, string& str);
istream& getline (istream&& is, string& str);
3、从文件中读取序列
打开文件,将序列写入到string中
ifstream inflie;
string s1;
inflie.open("file.txt", ios::in);
//先存到string中
getline(inflie,s1);
四、将string转为字符串类型。
头文件:#include <string.h> 和 #include <stdio.h>
功能:把从src地址开始且含有NULL结束符的字符串复制到以dest开始的地址空间
说明:src和dest所指内存区域不可以重叠且dest必须有足够的空间来容纳src的字符串。
返回指向dest的指针。
char *strcpy(char* dest, const char *src);
将string转为字符串
//string 转字符串
const int len = s1.length();
s = new char[len + 1];
strcpy(s, s1.c_str());
五、使用strtok()分割字符串
char *strtok(char s[], const char *delim);
功能:分解字符串为一组字符串。s为要分解的字符串,delim为分隔符字符串。
注意:如果传入字符串,则传入的字符串中每个字符均为分割符。首次调用时,s指向要分解的字符串,之后再次调用要把s设成NULL。
示例
include<iostream>
#include<cstring>
using namespace std;
int main()
{
char sentence[]="This is a sentence with 7 tokens";
cout << "The string to be tokenized is:\n" << sentence << "\n\nThe tokens are:\n\n";
char *tokenPtr=strtok(sentence," ");
while(tokenPtr!=NULL) {
cout<<tokenPtr<<endl;
tokenPtr=strtok(NULL," ");//第二次调用需要将s设置为NULL
}
//cout << "After strtok,sentence=" << tokenPtr<<endl;
return 0;
}