对于我的计算机科学课,我们被告知尝试从文本文档中读取并将其替换为C到C ++的每个字母
#include <iostream> // allows for cin and couts.
#include <fstream> // allows for the program to be able to read files.
using namespace std;
int main()
{
char str[1000000]; // used to store each letter.
int i = 0; // was supposed to be used as a counter to count the places of each letter within the array.
ifstream getExtraCredit(str); // opening file.
getExtraCredit.open("extracredit.txt");
char c;
if (!getExtraCredit) // If the read file isn't in the proper folder.
{
cout << "Error opening data file. " << endl;
}
else
{
while (getExtraCredit.get(c))
{
cout << c; // displays each character.
}
}
getExtraCredit.close(); // ends file reading.
system("PAUSE");
return 0;
}
extracredit.txt文件中的是
“C是世界上最现代化的编程语言之一。没有像C一样多才多艺的语言,C语言很有用。”
我对如何做到这一点非常困惑。网站上的一些帖子说要使用“替换”功能,但似乎只适用于字符串,而我的教师的具体说明是将它保存为字符数组。
根据我的理解,使用字符串而不是char更没意义吗?我很困惑的是如何使用chars这样做。如果我使用字符串,我对如何完成它的假设就是让项目读取文件并将其存储在字符串数组中。从那里,数组将被读取,如果它包含C,它将被C ++字符串替换。
他的导师是
创建一个程序proj5_3.cpp,它将读取输入的内容 将文件写回并输回所有字母“C”的输出文件 变成了“C ++”。输入/输出文件的名称完全取决于 您。例如,以下文件内容:
“C是世界上最现代化的编程语言之一 没有语言像C一样多才多艺,C语言很有用。“
应更改并保存到另一个文件中,并带有以下内容 含量:
“C ++是世界上最现代化的编程语言之一 没有语言像C ++那样多才多艺,C ++很有用。“
要从文件中读取一个字符,您应该使用get()函数:
ifstream inputFile; char next; ... inputFile.get(next);
首先编辑修订:
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string txt;
string temp;
ifstream getExtraCredit(txt); // opening file.
getExtraCredit.open("extracredit.txt");
if (!getExtraCredit)
{
cout << "Error opening data file. " << endl;
}
else
{
{
getline(getExtraCredit, temp); // displays each character.
txt.append(temp);
replace(txt.begin(), txt.end(), 'c', 'c++');
cout << txt;
}
}
getExtraCredit.close();
system("PAUSE");
return 0;
}
我现在遇到使用替换功能的问题。对我做错了什么的见解?
答案 0 :(得分:0)
如果我错了,请纠正我,但我认为应该是:
txt.replace(txt.begin(), txt.end(), 'c', 'c++');