简体   繁体   English

将char数组转换为C ++中的int

[英]char array to int in c++

I am unable to get the part of the string stored in form of char array. 我无法获取以char数组形式存储的字符串部分。

char code1 [12]={0};
char c;
string compressed_file;

I am taking the input from a text file, till a ',' occurs in it. 我正在从文本文件中获取输入,直到其中出现“,”。

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;

After printing the value of code1 here, I am only getting the first letter of the array. 在这里打印code1的值后,我只得到数组的第一个字母。 My code1 is 66 , it is printing only 6 . 我的code166 ,它只打印6

You are always saving in the position 0 : 您始终保存在位置0

int i=0; // this need to be out of while loop
code1[i]=c;
cout<<code1[i];

You need also to add a check for read at max 12 char (to not overflow code1 ). 您还需要添加最多12个字符的读取检查(不溢出code1 )。 The code could be something like. 代码可能像这样。

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

Move int i = 0 outside the loop . int i = 0 移到循环外 As it is, you are resetting it to 0 each time. 照原样,您每次都将其重置为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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM