更新:程序显示fstream的地址,而不是文本文件

Update: program shows adress of fstream instead of the text file

本文关键字:文本 文件 地址 程序 显示 fstream 更新      更新时间:2023-10-16

我即将编写一个程序,询问用户是否要"搜索或转换"文件,如果他们选择convert,则需要提供文件的位置。

我不知道为什么程序显示文件的地址而不是打开它。

这是我的第一个方法:

#include <fstream>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
char dateiname[64], kommando[64];
    ifstream iStream;

    cout << "Choose an action: " << endl <<
            " s - search " << endl <<
            " c - convert" << endl <<
            " * - end program" << endl;
    cin.getline(kommando,64,'n');
    switch(kommando[0])
    {
        case 'c':
            cout << "Enter a text file: " << endl;
            cin.getline(dateiname,64,'n');
            iStream.open("C://users//silita//desktop//schwarz.txt");
        case 's': break;
        case '*': return 0;
        default:
            cout << "Invalid command: " << kommando << endl;
    }
    if (!iStream)
    {
         cout << "The file " << dateiname << " does not exist." << endl;
    }
    string s;
    while (getline(iStream, s)) {
        while(s.find("TIT", 0) < s.length())
            s.replace(s.find("TIT", 0), s.length() - s.find("TIT", 3),"*245$a");
        cout << iStream << endl;
    }    
    iStream.close();
}

起初,您无法使用==比较c字符串。您必须使用strcmp(const char*, const char*)。你可以在那里找到更多关于它的信息:http://www.cplusplus.com/reference/cstring/strcmp/例如:if (i == "Konvertieren")必须成为if(!strcmp(i,"Konvertieren"))

正如Lassie的回答中所提到的,您不能使用c或c++以这种方式比较字符串;不过,为了充实它,我将解释为什么

char MyCharArr[] = "My Character Array"
// MyCharArr is now a pointer to MyCharArr[0], 
// meaning it's a memory address, which will vary per run 
// but we'll assume to be 0x00325dafa   
if( MyCharArr == "My Character Array" ) {
    cout << "This will never be run" << endl;
}

在这里,if将一个指针(MyCharArr)与一个字符数组文字进行比较,该指针将是一个内存地址,即一个整数。显然0x00325dafa!="我的角色阵列"。

使用cstrings(字符数组),您需要使用strcmp()函数,该函数将在cstring库中找到,它将为您提供一个数字,告诉您字符串的"不同程度",本质上为差异提供一个数值。在这种情况下,我们只对感兴趣,没有区别,它是0,所以我们需要的是:

#include <cstring>
using namespace std;
char MyCharArr[] = "My Character Array"
if( strcmp(MyCharArr,"My Character Array")==0 ) { 
    // If there is 0 difference between the two strings...
    cout << "This will now be run!" << endl;
}

虽然你的问题中没有这样做,但如果我们使用c++字符串而不是字符数组,我们会使用compare()方法来产生类似的影响:

#include <string>
using namespace std;
string MyString = "My C++ String"
if( MyString.compare("My C++ String")==0 ) { 
    // If there is 0 difference between the two strings...
    cout << "This will now be run!" << endl;
}