尝试从文本文件中读取列表,然后搜索文本文件,并在c++中提取字符串
Trying to read off a list from a text file, then search the text file, and extract a string in C++
所以现在我正在尝试编写一个程序,它接受用户输入的日期,如:02/04/1992,并输出日期如下:1992年4月2日。与在程序中以字符串或其他形式显示相应的日期不同,我有一个文本文件,其日期以列表形式显示,如下所示:
1月01 2月02 3月03. .等等......
我知道我必须使用string.find(),但我不确定我应该使用什么参数。到目前为止,我有这个:
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
string thedate; //string to enter the date
string month; // this string will hold the month
ifstream myfile ("months.txt");
cout << "Please enter the date in the format dd/mm/yyyy, include the slashes: " << endl;
cin >> thedate;
month = thedate.substr( 3, 2 );
string newmonth;
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,newmonth);
cout << newmonth.find() << endl;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
我已经检查了查找函数在线,但我仍然不明白我将使用什么参数。现在,在我的程序中,格式为mm的月份存储在字符串month中;我不知道如何在文本文件中搜索month;里面的内容,并返回该行的其余部分。例如,05会变成May。我还没学过数组,所以如果我能远离数组就太棒了。
谢谢。
不需要使用find.
while ( myfile.good() )
{
getline (myfile,newmonth);
if ( newmonth.substr(0,2) == month) {
cout << newmonth.substr(2) << endl;
}
}
我想我会以不同的方式组织事情。我在开始时读取了整个文件(显然是12行),使用数字来确定在数组中存储相关字符串的位置。然后,当用户输入日期时,您只需使用他们的数字来索引该数组,而无需搜索它。
int number;
std::string tmp;
std::vector<std::string> month_names(12);
while (myfile >> number) {
myfile >> tmp;
month_names[number] = tmp;
};
std::string get_name(int month) {
return month_names[month];
}
相关文章:
- 文本文件中的单词链表
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 如何将内容数组写入文本文件?
- 无法通过空白将文本文件行分隔为矢量
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- C++将文本文件中的数据读取到结构数组中
- 在指针的帮助下,文本文件中单词的频率
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 将值从二维数组输出到文本文件
- 如何在c++中从文本文件中逐行读取整数
- 从文本文件中读取时钟时间和事件时间并进行处理
- 如何从文本文件中读取值和数组
- 如何在C++中确定文本文件中的元素是字符还是数字
- C++试图读取一个文件并输出到另一个文本文件
- 如何通过套接字将文本文件的内容从服务器发送到客户端
- 已修改的LinkedList未在文本文件本身中更新
- C++文本文件的获取线
- 为什么C++的文件 I/O 在读取文本文件时忽略初始空行?我怎样才能让它不这样做?
- 打印逐行存储的文本文件
- C++文本文件输入