【发布时间】:2015-11-12 07:25:13
【问题描述】:
我决定在明年参加正式课程之前开始学习 C++,我已经从 CodeEval 和 Project Euler 的一些简单挑战开始。在这一个中,您必须获取一个包含单词字符串的输入文件,并且您必须输出文件的行,并将单词反转。这样一个具有以下输入的文件
1:这是第一行
2:这是第二行
最终会变成
1:一行是This
2:两行是This
我编写了以下程序来做到这一点,除了没有正确反转字符串,而是完全反转单词之外,尽管编译没有错误或警告,但它还是出现了分段错误。我假设我错过了一些关于 C++ 中正确内存管理的内容,但我不确定它是什么。那么有人可以告诉我我在内存管理方面错过了什么吗?
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
int main(int argc, char** argv)
{
std::string filename = argv[1]; //has to be argv[1], argv[0] is program name
std::string output_string; //final output
std::string line; //Current line of file
std::ifstream read(filename.c_str());
if(read.is_open()){
while(std::getline(read,line)){
std::string temp;
std::istringstream iss;
iss.str(line);
while(iss >> temp){ //iterates over every word
output_string.insert(0,temp); //insert at the start to reverse
output_string.insert(0," "); //insert spaces between new words
}
output_string.erase(0,1); //Removes the space at the beginning
output_string.insert(0,"\n"); //Next line
}
output_string.erase(0,1); //Remove final unnecessary \n character
read.close();
}
else{
std::cout<<"Unable to open file\n";
}
for(unsigned int i = output_string.length(); i>=0;i--){
std::cout<<output_string[i];
}
std::cout<<"\n";
}
【问题讨论】:
标签: c++ string file memory-management