簡體   English   中英

將char數組轉換為C ++中的int

[英]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的值后,我只得到數組的第一個字母。 我的code166 ,它只打印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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM