我有一个名为myfile.txt
的文本文件,其中列出了驱动器D:\
的内容。在我的计划中,我有一个功能,将会阅读myfile.txt
。它将从.txt
扩展名中提取文件名。我不太了解C ++,所以你能说“简单”吗?我对子串的起始位置感到困惑,因为我怎么知道从哪里开始。
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main(void)
{
system("cls");
string temp;
fstream file;
file.open("D:\\myfile.txt", ios::in);
while( file.good() )
{
file>>temp;
string str2, str3;
size_t pos;
str2 = temp.substr (4,4); // confused with this
pos = temp.find(".txt"); // position of ".txt" in temp
str3 = temp.substr (pos);
cout << str2 << ' ' << str3 << endl;
}
system("pause");
return 0;
}
答案 0 :(得分:4)
答案 1 :(得分:4)
答案 2 :(得分:0)
#include <fstream>
#include <vector>
#include <string>
int main (int argc, char* argv[])
{
if (argc != 2)
return 1;
std::ifstream file(argv[1]);
if (!file.is_open())
return 2;
std::vector<std::string> files;
std::string line;
while (std::getline(file, line)) {
if(line.length() < 4)
continue;
if(line.substr(line.length() - 4, std::string::npos) == ".txt")
files.push_back(line);
}
/* all files ending with .txt are in "files" */
return 0;
}
答案 3 :(得分:0)
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
// inspried by http://www.cplusplus.com/reference/std/iterator/istream_iterator/
struct getline :
public std::iterator<std::input_iterator_tag, std::string>
{
std::istream* in;
std::string line;
getline(std::istream& in) : in(&in) {
++*this;
}
getline() : in(0) {
}
getline& operator++() {
if(in && !std::getline(*in, line)) in = 0;
}
std::string operator*() const {
return line;
}
bool operator!=(const getline& rhs) const {
return !in != !rhs.in;
}
};
bool doesnt_end_in_txt(const std::string& s) {
if (s.size() < 4)
return true;
if (s.compare(s.size()-4, 4, ".txt") != 0)
return true;
}
int main() {
std::vector<std::string> v;
std::remove_copy_if(getline(std::cin), getline(),
std::back_inserter(v),
doesnt_end_in_txt);
}