【问题标题】:How do i take integers from a file and place them in an int vector?如何从文件中获取整数并将它们放入 int 向量中?
【发布时间】:2011-10-05 10:56:55
【问题描述】:

我正在尝试获取一个文本文件并获取文件中的整数并将它们传输到一个向量中,该向量可以读取到不同的函数中。

这是我目前所拥有的:

int main(int argc, char *argv[] )
{
vector<int> buff;
argv[1] = "input_24_0.txt";

if (argc < 2)
{
    std::cout << "usage: " << argv[0] << " <filename>\n";
    return 2;
}
std::ifstream fin(argv[1]);
if (fin)
{
    std::stringstream ss;
    // this copies the entire contents of the file into the string stream
    ss << fin.rdbuf();
    // get the string out of the string stream
    std::string contents = ss.str();
    std::cout << contents;
    // construct the vector from the string.
    std::vector<int> buff(contents.begin(), contents.end());
}
else 
{
    std::cout << "Couldn't open " << argv[1] << "\n";
    return 1;
}

clock_t t1, t2, t3, t4;

int maxSum;

t1 = clock();
maxSum = maxSubSum1(buff);
cout << "MaxSubSum1 is " <<  maxSum << endl;
cout << double( clock() - t1 )
/ (double)CLOCKS_PER_SEC<< " seconds." << endl;
t1 = clock() - t1;

t2 = clock();
maxSum = maxSubSum2( buff );
cout << "MaxSubSum2 is " <<  maxSum << endl;
cout << double( clock() - t2)
/ (double)CLOCKS_PER_SEC<< " seconds." << endl;
t2 = clock() - t2;

t3 = clock();
maxSum = maxSubSum3(buff );
cout << "MaxSubSum3 is " <<  maxSum << endl;
cout << double( clock() - t3 )
/ (double)CLOCKS_PER_SEC<< " seconds." << endl;
t3 = clock() - t3;

t4 = clock();
maxSum = maxSubSum4( buff );
cout << "MaxSubSum4 is " <<  maxSum << endl;
cout << double( clock() - t4 )
/ (double)CLOCKS_PER_SEC<< " seconds." << endl;
t4 = clock() - t4;

system("pause");

return 0;
 }

【问题讨论】:

  • NG:**argv[1] = "input_24_0.txt";**,局部重定义?:std::vector buff(contents.begin(), contents.end() );

标签: c++ argv argc


【解决方案1】:

如果文件中的数字以空格分隔,您可以执行以下操作:

 std::ifstream iStream;
 iStream.open("filename.ext");
 int tempVariable;

 if (iStream) {
   while (iStream >> tempVariable) {
      // Any routines to check the value of the number if necessary
      vector.push_back(tempVariable);
   }
   iStream.close();
 }
 else
   // Error routine

如果数字没有用空格分隔,您可以使用字符串流方法,并循环遍历将每个 char 转换为其十进制值的流。

【讨论】:

  • 对不起.. 我试图提供代码外观的 sn-p。显然,您将声明一个 int 变量,您将一次将值放入一个中,对从文件中读取的值进行任何必要的检查,然后将其存储在向量中。
  • 是的,我将 tempVariable 声明为 int。我以为。它不需要任何例程,它会将所有整数放入一个向量中,这样我就可以在我的程序的其他函数的参数中使用该向量。
  • 那么上面放置在 main() 函数中的代码示例将在假设值由空格(空格、制表符、换行符等)分隔的情况下工作。
  • 我的函数接受这些参数:int maxSubSum4(const vector & a);
  • 把参数改成maxSubSum4(vector& a);删除 'const' 关键字。 const 使它成为只读的。
猜你喜欢
  • 1970-01-01
  • 2015-04-09
  • 2019-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多