【问题标题】:char array to int in c++char数组到C++中的int
【发布时间】:2014-11-30 22:35:43
【问题描述】:

我无法获取以 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

【问题讨论】:

  • 考虑使用std::vector&lt;char&gt; 而不是您的数组。这可以实现更长的输入,并且您不需要变量i,而是选择back() 元素。

标签: c++ arrays char int


【解决方案1】:

你总是在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;
}

【讨论】:

    【解决方案2】:

    int i = 0 移出循环。实际上,您每次都将其重置为 0

    input>>c;
    int i=0; //move to here
    while(c != ',')
    {        
        code1[i]=c;
        cout<<code1[i];
        i++;
        input>>c;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-07
      • 2010-09-22
      • 2023-03-23
      • 2012-05-06
      • 1970-01-01
      • 2012-12-25
      相关资源
      最近更新 更多