我即将编写一个程序,询问用户是否要“搜索或转换”文件,如果他们选择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();
}
答案 0 :(得分:2)
首先,您无法使用==
比较c字符串。您必须使用strcmp(const char*, const char*)
。有关它的更多信息,你可以在那里找到:http://www.cplusplus.com/reference/cstring/strcmp/
例如:if (i == "Konvertieren")
必须变为if(!strcmp(i,"Konvertieren"))
答案 1 :(得分:0)
正如Lassie的回答所提到的,你不能用c或c ++这样比较字符串;然而,为了充实它,我会解释为什么。
0px
这里if将一个指针(MyCharArr)与一个字符数组文字进行比较,该指针是一个内存地址,即一个整数。显然是0x00325dafa!=“我的角色阵列”。
使用cstrings(字符数组),你需要使用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;
}
库中的strcmp()
函数,它会给你一个数字,告诉你字符串“有多么不同”,基本上给出差值的数值。在这个例子中,我们只对 no difference 感兴趣,它是0,所以我们需要的是:
cstring
虽然你没有在你的问题中这样做,但如果我们使用的是c ++字符串而不是字符数组,我们会使用#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;
}
方法来实现类似的效果:
compare()