char数组到c ++中的int

Yas*_*ash 1 c++ arrays int char

我无法获取以char数组的形式存储的字符串部分.

char code1 [12]={0};
char c;
string compressed_file;
Run Code Online (Sandbox Code Playgroud)

我从文本文件中获取输入,直到出现','.

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;
Run Code Online (Sandbox Code Playgroud)

在这里打印code1的值后,我只得到数组的第一个字母.我code166,它只打印6.

Net*_*peC 5

你总是保存在这个位置0:

int i=0; // this need to be out of while loop
code1[i]=c;
cout<<code1[i];
Run Code Online (Sandbox Code Playgroud)

您还需要添加一个最大12字符读取检查(不溢出code1).代码可能是这样的.

input >> c;
int i = 0;
while (c != ',' && i < sizeof(code1)) {
    code1[i] = c;
    cout << code1[i];
    i++;
    input >> c;
}
Run Code Online (Sandbox Code Playgroud)