40 Mars Bar40 Toffee Crisp30 Kit Kat25 Toblerone40 Bounty50 Topic0前面为价钱后面为商品名 保存在一个txt文件中如何读取价钱和商品名并且保存在2个数组中0为结束标志 读到0停止 上面的信息都存在一个txt文件中把价钱和商品名分别读取出来 用于下面的程序
3 回答
ibeautiful
TA贡献1993条经验 获得超5个赞
getline会生成一个包含一串从输入流读入的字符的字符串,直到以下情况发生会导致生成的此字符串结束。1)到文件结束,2)遇到函数的定界符,3)输入达到最大限度。
函数原型:
(1)istream& getline (istream& is, string& str, char delim);
(2)istream& getline (istream& is, string& str);
其中:delim 为终结符,第二种形式 delim默认为 '\n'(换行符)。
例子:(2)
#include<iostream> #include<fstream> #include<string> using namespace std; int main() { string buff; ifstream infile; ofstream outfile; cout<< "Input file name: " <<endl; cin>>buff; infile.open(buff.c_str()); if (!infile) cout<< "error" <<buff<<endl; cout<< "Input outfile name: " <<endl; cin>>buff; outfile.open(buff.c_str()); while (getline(infile, buff)) outfile<<buff<<endl; infile.close(); outfile.close(); return 0; } |
皈依舞
TA贡献1851条经验 获得超3个赞
getline的原型如下:
getline(char* c,int i,char c); 表示读入i个字符,或者遇到结束符c为止的字符数,保存到c中。
getline(char*,int); 表示读入i个字符到c中。注意读入的字符数应比实际的大1,因为读入的是字符串,字符串将会以'\0'作为结束,如果你要读入3个字符,那么i的值应该为4。
注意getline会读取并丢弃分界符。
后面的自已搞定,创建一个文件流类对象,然后用这个文件流来调用getline函数,比如
ifstream hy1(“hyong1.txt”)//创建hy1流,并打开文件以便读取内容。
char c[333];
hy1.getline(c,3,'0'); //表示,把hy1流关联的hyong1中3个字符或者遇到'0'的字符数读入到c中。
添加回答
举报
0/150
提交
取消