[英]char array to int in c++
我无法获取以char数组形式存储的字符串部分。
char code1 [12]={0};
char c;
string compressed_file;
我正在从文本文件中获取输入,直到其中出现“,”。
cout<<"Input compressed_file name"<<endl;
cin>>compressed_file;
string extracted_file;
cout<<"Input extracted_file name"<<endl;
cin>>extracted_file;
ifstream input;
input.open(compressed_file.c_str());
ofstream decompresscode;
decompresscode.open(extracted_file.c_str());
input>>c;
while(c != ',')
{
int i=0;
code1[i]=c;
cout<<code1[i];
i++;
input>>c;
}
int old=atoi(code1);
cout<<old;
在这里打印code1的值后,我只得到数组的第一个字母。 我的code1
是66 ,它只打印6 。
您始终保存在位置0
:
int i=0; // this need to be out of while loop
code1[i]=c;
cout<<code1[i];
您还需要添加最多12个字符的读取检查(不溢出code1
)。 代码可能像这样。
input >> c;
int i = 0;
while (c != ',' && i < sizeof(code1)) {
code1[i] = c;
cout << code1[i];
i++;
input >> c;
}
将int i = 0
移到循环外 。 照原样,您每次都将其重置为0
。
input>>c;
int i=0; //move to here
while(c != ',')
{
code1[i]=c;
cout<<code1[i];
i++;
input>>c;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.