PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, November 2, 2022

[FIXED] How to read all integers into array from input file in C++

 November 02, 2022     arrays, c++, file     No comments   

Issue

So let's say I have a file like this: 1 23 14 abc 20

It will read the numbers 1, 23, 14, but I also want it to read the value 20 into the array. How can I accomplish this?

#include <iostream>
#include <fstream>
using namespace std;

int main(){
    const int ARRAY_SIZE = 1000;
    int numbers[ARRAY_SIZE], count = 0;
    double total = 0, average;

    ifstream inputFile;

    if(argc == 2){
        inputFile.open(argv[1]);
    }
    else{ 
        cout << "Invalid" << endl;
        return 1;
    }
    while (count < ARRAY_SIZE && inputFile >> numbers[count]){
         count++;
    }
    inputFile.close();
    ...

Solution

Here's how I would do it. I added comments to the code to explain the intent and used a std::vector<int> instead of an array with a hardcoded size since you didn't mention any restrictions and I feel it is a better way to handle the problem. If you must used a statically sized array you should be able to adapt this.

#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
#include <string>

// Avoid using namespace std;

std::vector<int> readData(std::istream& input)
{
    // In general prefer std::vector for variable sized data
    std::vector<int> ret;
    std::string word;
    std::stringstream ss;

    while (input >> word)
    {
        // Clear error flags and set the conversion stream to the value read.
        ss.clear();
        ss.str(word);

        int val = 0;
        // The first condition will fail if the string doesn't start with a digit
        // The second will fail if there is still data in the stream after some of
        // it was converted.
        if (ss >> val && ss.eof())
        {
            ret.push_back(val);
        }
    }
    return ret;
}

int main()
{
    // In your code open the file and pass the stream to
    // the function instead of std::cin
    auto v = readData(std::cin);
    for (auto n : v)
    {
        std::cout << n << " ";
    }
    std::cout << "\n";
}
Input: 1 23 14 abc 20 123xyz 50 nope 12345 a 100
Output: 1 23 14 20 50 12345 100

Working example: https://godbolt.org/z/ab87KjzjK



Answered By - Retired Ninja
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing