Как мне взять целые числа из файла и поместить их в вектор INT? - PullRequest
0 голосов
/ 05 октября 2011

Я пытаюсь взять текстовый файл и взять целые числа внутри файла и перенести их в вектор, в котором можно прочитать различные функции.

Вот что у меня есть:

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;
 }

1 Ответ

0 голосов
/ 05 октября 2011

Если числа в файле разделены пробелами, вы можете сделать следующее:

 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 в десятичное значение.

...