我正在创建一个C ++程序,该程序读取具有内容的文本文件
San Jose, 2, 10 , 1<br/> Sunnyvale, 2, 5, 4<br/> Gilroy, 8, 4, 3<br/> Oakland, 5, 8, 9<br/> mountain View, 7, 5, 12<br/> Santa Clara, 6, 4, 6<br/> Fremont, 1, 2, 0<br/> Belmont, 4, 9, 5<br/>
我的尝试是将所有数字存储在矩阵(8x3)中。这是我的代码
int main () {
vector <vector <string> > data;
ifstream infile( "test.txt" );
int data_row = 0;
while (infile)
{
string s;
if (!getline( infile, s )) break;
data_row++;
istringstream ss( s );
vector <string> record;
while (ss)
{
string s;
if (!getline( ss, s, ',' )) break;
record.push_back( s );
}
data_column = record.size() - 1;
data.push_back( record );
}
if (!infile.eof())
{
cerr << "Fooey!\n";
}
cout << data_row << " " << data_column << "\n";
data_type** m_value;
m_value = new data_type*[data_row];
for(int i=0;i<data_row;i++) {
m_value[i] = new data_type[data_column];
}
vector<string>myvector;
for (int i = 0; i < data.size(); i++) {
for (int j = 0; j < data[i].size(); j++) {
cout << i << "****" << j << " " << data[i][j] << "\n ";
if ( j != 0) {
myvector.push_back(data[i][j]);
}
}
}
for(int i=0;i<data_row;i++) {
for(int j=0;j< data_column;j++) {
for (int k = 0; k < myvector.size(); k++) {
cout << k << " " << myvector[k] << "\n";
m_value[i][j] = myvector[k];
}
}}
程序因getline.cpp:57:24而失败:错误:无法转换
将'std :: basic_string'分配为'int'
m_value [i] [j] = myvector [k];
请帮助我解决问题
谢谢
答案 0 :(得分:0)
std::stoi
将字符串转换为整数。如果您使用十进制数字,请使用std::stod
。这意味着将字符串加倍m_value[i][j] = std::stoi(myvector[k]);
答案 1 :(得分:0)
请去吃/读一本有关C ++的好书
#include <cstddef>
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <vector>
#include <iterator>
template<typename T, std::size_t N>
std::size_t sizeof_array(T(&)[N])
{
return N;
}
struct record
{
std::string name;
int a;
int b;
int c;
};
std::istream& operator>>(std::istream &is, record &r)
{
record tmp;
std::getline(is, tmp.name, ',');
char ch;
int *dst[] = { &tmp.a, &tmp.b, &tmp.c };
for (std::size_t i{}; i < sizeof_array(dst); ++i)
{
if(!( is >> *dst[i] ))
return is;
if (i < sizeof_array(dst) - 1)
is >> ch;
}
while (is.peek() != '\n' && is.peek() != EOF)
is.get();
is.get();
r = tmp;
return is;
}
std::ostream& operator<<(std::ostream &os, record const &r)
{
os << r.name << '\t' << r.a << '\t' << r.b << '\t' << r.c;
return os;
}
int main()
{
constexpr char const *input_file_name{ "input.txt" };
std::ifstream input_file{ input_file_name };
if (!input_file) {
std::cerr << "Failed to open \"" << input_file_name << "\" for reading!\n\n";
return EXIT_FAILURE;
}
std::vector<record> data{ std::istream_iterator<record>{input_file}, std::istream_iterator<record>{} };
for (auto const &d : data)
std::cout << d << '\n';
}