c++ - 输出复制的字符串时出现问题

标签 c++ string

这已经给我带来了一段时间的麻烦,我对代码所做的任何调整似乎都没有什么不同。 我试图在从文件中读取的一行文本中找到数字,并将所述数字存储到另一个字符串中以备后用。最初的复制似乎是成功的,但是当尝试输出存储数字的字符串时,唯一的输出是一个空行。

这是代码和包含的头文件:

#include<iostream>
#include<string>
#include<fstream>
#include<cctype>

using namespace std;

int main()
{
    ifstream inFile;
    string temp;
    short count = 0;
    char fileName[20];  
    string info1;

    cout << "Enter the name of the file to be used: " << endl;
    cin >> fileName;

    inFile.open(fileName);

    if(!inFile)
    {
        cout << "Error opening file." << endl;      
    }
    else
    {           
        getline(inFile, info1);
        cout << info1 << endl;

        for(short i = 0; i < info1.length(); i++)
        {
            if(isdigit(info1[i]))
            {   
                temp[count] = info1[i];
                cout << temp[count] << endl;
                count++;
            }
        }
        cout << temp << endl;
    }   
    inFile.close();
    return 0;
}

输出如下:

Enter the name of the file to be used:
input.txt
POPULATION SIZE: 30
3
0

显然,它没有按预期输出 temp。 如有任何帮助或建议,我们将不胜感激。

最佳答案

问题是 temp 不是简单的字符数组。它是 std::string 类。最初 temp 是空的。这意味着我们不知道为字符串分配了多少内存。它甚至可以是 0。因此,当您将 std::string::operator[] 应用于空字符串时,请引用应该返回什么符号?

您应该改用 std::string::operator+= 或 char 数组。

关于c++ - 输出复制的字符串时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13208900/

相关文章:

c++ - SDL2 渲染文本问题

c++ - 将 gettext 与本地目录一起使用无效

java - 获取剪贴板字符串编码 (java)

c++ - 文件输入,尝试从字符串中提取 Int (C++)

python - 围绕未指定的任何字符拆分字符串

c++ - 从 GPU 复制到 CPU 比从 CPU 复制到 GPU 慢

c++ - 无效转换错误和无效类型

c++ - 在C++中调整pdf文件内容

c++ - C 标记化多项式系数

java - 如何打印我的 Java 对象而不得到 "SomeType@2f92e0f4"?