【发布时间】:2014-02-22 11:10:15
【问题描述】:
我已经阅读了一些关于将字符串转换为整数的 StackExchange 帖子和其他页面,但这不起作用。这是我尝试的最后一件事:
if (infile.is_open())
{
while (getline (infile,line))
{
regex_match(line,matches,exp);
regex_match((string)matches[1], time0, exp_time);
buffer << time0[1];
str = buffer.str();
str.append("\0");
cout << atoi(str.c_str()) << '\n';
last_match = matches[2];
buffer.str(string());
}
infile.close();
}
我想不出任何其他方法。我尝试了正常的将字符串转换为 char * 到整数的转换。我尝试将其转换为字符串,然后使用 stoi() 将其转换为整数。我尝试将 NULL 字符(“\0”)附加到它,我也尝试将它附加到缓冲区中。我还尝试了 atof() 和 stof()。 stoi() 和 stof() 都会使程序崩溃。 atoi() 和 atof() 总是返回 0。
这是一个SSCCE,其中包含问题(atoi(str.c_str()) 不应为 0):
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <iostream>
#include <fstream>
#include <string>
#include <regex>
#include <sstream>
using namespace std;
int main(int argc, char* argv[])
{
regex exp("^(.+),(.+),.+,.+,(.+),.+,.+$");
regex exp_time("^(.+)-(.+)-(.+)");
smatch matches;
smatch time0;
string line;
ifstream infile(argv[1]);
string last_match;
stringstream buffer;
string str;
int i = 0;
if (infile.is_open())
{
while (getline(infile, line))
{
regex_match(line, matches, exp);
regex_match((string)matches[1], time0, exp_time);
buffer << time0[1];
str = buffer.str();
str = time0[1].str();
str.append("\0");
cout << atoi(str.c_str()) << " " << time0[1] << '\n';
last_match = matches[2];
buffer.str(string());
i++;
}
infile.close();
}
return 0;
}
输入将是具有以下值的 csv 文件:
1996-09-04,19.00,19.25,18.62,18.87,528000,0.79
1996-09-03,19.00,19.37,18.75,19.00,1012800,0.79
1996-08-30,19.87,20.12,19.37,19.62,913600,0.82
1996-08-29,20.87,21.12,19.75,19.75,1987200,0.82
1996-08-28,20.12,22.12,20.12,21.12,5193600,0.88
1996-08-27,19.75,20.37,19.75,20.12,1897600,0.84
1996-08-26,20.12,20.12,19.75,19.75,388800,0.82
1996-08-23,19.75,20.25,19.75,19.75,1024000,0.82
1996-08-22,18.62,20.00,18.25,19.87,1921600,0.83
1996-08-21,19.12,19.25,18.25,18.62,688000,0.78
1996-08-20,19.62,19.62,19.12,19.12,494400,0.80
1996-08-19,19.37,19.62,19.37,19.62,428800,0.82
1996-08-16,19.50,19.87,19.12,19.37,864000,0.81
您可以使用program.exe filename.csv 运行程序
这是一个更短的程序,问题更明显:
【问题讨论】:
-
您使用的是哪种输入字符串和正则表达式?你确定你得到一个类似于数字的字符串吗?
-
请写一个显示所有定义的简单测试用例
-
您是否验证过正则表达式确实匹配并且结果中的第二项存在?
-
time0和matches有什么类型?此外,提供SSCCE 总是好的。 -
我添加了一个 SSCCE 和一些示例输入。
标签: c++ regex string char atoi