更新:程序显示fstream的地址,而不是文本文件
Update: program shows adress of fstream instead of the text file
我即将编写一个程序,询问用户是否要"搜索或转换"文件,如果他们选择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;
}
相关文章:
- 文本文件中的单词链表
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 如何将内容数组写入文本文件?
- 无法通过空白将文本文件行分隔为矢量
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- C++将文本文件中的数据读取到结构数组中
- 在指针的帮助下,文本文件中单词的频率
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 将值从二维数组输出到文本文件
- 如何在c++中从文本文件中逐行读取整数
- 从文本文件中读取时钟时间和事件时间并进行处理
- 如何从文本文件中读取值和数组
- 如何在C++中确定文本文件中的元素是字符还是数字
- C++试图读取一个文件并输出到另一个文本文件
- 如何通过套接字将文本文件的内容从服务器发送到客户端
- 已修改的LinkedList未在文本文件本身中更新
- C++文本文件的获取线
- 为什么C++的文件 I/O 在读取文本文件时忽略初始空行?我怎样才能让它不这样做?
- 打印逐行存储的文本文件
- C++文本文件输入