C++ - How to input space separated numbers into array? - c++

I have this file:
4
10 3 4 6
The first line declares how many numbers the second line has.I want to put the numbers of the second line in an array.So far i have been using this loop to automatically declare how many numbers the second line has and how many times to do the loop:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main(){
ifstream infile;
infile.open("input.in");
string kids;
int x;
int i;
getline(infile,kids);
cout << "The Number Of Kids Is " << kids << endl;
istringstream buffer(kids);
int kidss;
buffer >> kidss;
for(i=0;i<kidss;i++){
infile >> x;
cout << x << " ";
}
infile.close();
return 0;
}
Now i want to do the same thing but instead of inputing the numbers in x i want to put them in an array and then display them as above.Thanks In Advance!

The best way of doing this would be with a std::vector these are variable length arrays in c++.
To use them in this case you would do
std::vector<int> array;
for( int i = 0 ; i < kidss ; ++i ) {
infile >> x;
array.push_back(x);
}
Then if you wanted to print them out again you would be able to do
for( int i = 0 ; i < array.size() ; ++i ) {
std::cout << array[i] << " ";
}

Related

How to get the average from data.txt file with C++?

Our professor wants us to fix the code which counts the amount of values in a data.txt file and computes their average. Here is the code:
#include <cstdlib>
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
int main(int argc, char *argv[])
{
string s;
ifstream f;
int nItems;
double * data;
double sum=0;
vector < double > data2;
double item;
cout <<"File name: ";
cin >> s;
f.open (s.c_str() );
while (! f.eof() )
{
f >> item;
data2.push_back(item);
}
for (int i =0; i < nItems; i++)
{
sum += data[i];
}
cout << "The average is " << sum/nItems <<".\n";
cout << "Press the enter key to continue ...";
cin.get();
return EXIT_SUCCESS;
}
His instructions were:
Modify code worked on today so that the average of data in vector < double > data is computed properly. Right now the code just gives you a value which isn't the average.
I tried changing the nItems variable into 12 and that seemed to work, but the goal of the code is to determine nItems and use that to find the average, which I can't seem to figure out.
You use data for which you haven't allocated any memory when you summarise That causes undefined behaviour. You've stored your values in data2. Remove variables you don't need. Also, using namespace std is considered bad practice.
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <numeric> // std::accumulate
int main(int, char**) {
std::string filename;
std::cout << "File name: ";
std::cin >> filename;
std::ifstream f(filename); // no need for .c_str()
std::vector<double> data;
double item;
// instead of checking for eof, check if extraction succeeds:
while(f >> item) {
data.push_back(item);
}
// a standard way to sum all entries in a container:
double sum = std::accumulate(data.begin(), data.end(), 0.);
std::cout << "The sum is " << sum << "\n";
// use the containers size() function. it returns the number of items:
std::cout << "The average is " << (sum / data.size()) << "\n";
}
Hey looks like you weren't reading the numbers in from the txt file.
Here I look through the input file once just to count how many numbers there are
so I can make the array.
Then I look through it again to fill the array.
#include <cstdlib>
#include <iostream>
#include <fstream>
// f here stands for find, fstream gives you files
using namespace std;
int main(int argc, char *argv[]) {
string s;
ifstream f;
// input file stream
int nItems;
double * data;
double sum=0;
cout << "File name: ";
cin >> s;
f.open (s.c_str() );
// s.c_str will return a char array equivalent of the string s
nItems=0;
int input =0;
while (f >> input) {//first loop reading through file to count number of items
nItems++;
}
f.close();
data = new double[nItems]; //Make the array
f.open (s.c_str() );//open file for second read
int i=0;
while (f >> input) {//Second loop through file fills array
data[i] = input;
i++;
}
f.close();
for (int i = 0; i < nItems; i++) {
sum += data[i];
}
cout << "The average is " << sum / nItems << ".\n";
cout << endl;
system("pause");
return 0;
}

How to read from keyboard a variable number of integers in C++?

I need to read a variable number of integers from keyboard so that I can use each of them.
First I thought I could use something like
int myinteger;
for (int i=0; i<MAX_NUMBER_OF_INTEGERS; i++){
cin >> myinteger;
//What I want to do with that Integer
}
But then I realized that if MAX_NUMBERS_OF_INTEGERS = 10 I have to write 10 integers. But what I want is that I can pass "1 2 3" "1 2 3 4" (for example) and not necessary write 10 integers.
The question seems to have changed a little bit since it was asked and a good answer was given. This just serves to answer the new questions.
#include <iostream>
#include <sstream>
#include <vector>
const int MAX_NUMBERS_OF_INTEGERS = 10;
int main() {
std::string line;
std::cout << "Enter at most " << MAX_NUMBERS_OF_INTEGERS << " ints, separated by spaces: ";
std::getline(std::cin, line);
// create a string stream of the line you entered
std::stringstream ss(line);
// create a container for storing the ints
std::vector<int> myInts;
// a temporary to extract ints from the string stream
int myInteger;
// extract at most MAX_NUMBERS_OF_INTEGERS ints from the string stream
// and store them in the container
while(myInts.size()<MAX_NUMBERS_OF_INTEGERS && ss>>myInteger) myInts.push_back(myInteger);
std::cout << "Extracted " << myInts.size() << " integer(s)\n";
// loop through the container and print all extracted ints.
for(int i : myInts) {
std::cout << i << "\n";
}
// ... or access a certain int by index
if(myInts.size() > 2)
std::cout << "The third int was: " << myInts[2] << "\n";
}
std::vector<int> read_ints;
int _temp;
for(;;)
{
cin >>_temp;
if(!cin.good()) {
break;
}
else {
read_ints.push_back(_temp);
}
}
I haven't tested this solution but it should read an arbitrary number of ints from cin until you enter something else than an integer. You could also skip the saving in the vector part if you don't need to save the results. This is just releveant if you want to save an arbitray number of integers.
EDIT: After clarification your solution could look like this:
int MAX_CHARS = 10;
int my_int;
cin >> setw(MAX_CHARS) >> my_int;
setw limits the number of input characters but you have to include iomanip header
If you want to access every digit, convert int to vector of ints with this function:
vector <int> integerToArray(int x)
{
vector <int> resultArray;
while (true)
{
resultArray.insert(resultArray.begin(), x%10);
x /= 10;
if(x == 0)
return resultArray;
}
}
then you can access each digit with the index e.g. first digit
vectory<int> resultArray = integerToArray(my_int);
int digit = resultArray[0];
Source
One way to read all numbers from a single line limiting them to a maximum number of integers is using std::getline() to get the line into a string then use istringstream in a loop.
#include <iostream>
#include <sstream>
using namespace std;
int main() {
std::string line;
std::getline (std::cin,line);
std::istringstream iss(line);
int myInt;
for(int i=0;(iss >> myInt) && (i < MAX_NUMBER_OF_INTEGERS);++i ) {
std::cout << myInt << ' ';
}
return 0;
}
Note: I did not define MAX_NUMBER_OF_INTEGERS in the code. I could have defined it with const int MAX_NUMBERS_OF_INTEGERS = 10; before usage or possibly that could be a preprocessor define or even a command line parameter. I leave this up to the user.

How can I get the second and last characters of a line for an input file and compose array in C++?

I have an input.txt file, I am trying to read input file by line and I want to compose 2 arrays. First line after space gives the size of the array. Size of the array is 3 for my example input file which is below. From second line after first space till end of the file composes array A[]. For this example A[3]={5,8,14} From Second line after second space till end of the input file composes content of array B[]. It is B[3]={67,46,23} for this input file. After first line first numbers of every line is just gives the line number of each line.Input file is like that:
10 3
1 5 67
2 8 46
3 14 23
Here is the below my start code. How can I get the second and last characters of a line for an input file?
#include<stdio.h>
#define N 128
#include <iostream>
#include <fstream>
int A[N];
int B[N];
int main(){
ifstream fin;
fin.open("input.txt", ios::in);
char CHARACTER;
int ITEMNUMBER = 0;
while (!fin.eof() ) {
fin.get(CHARACTER);
if (CHARACTER== '\n'){
++ITEMNUMBER;
}
}
printf("\n");
cout << "NUMBER OF ITEMS: " << ITEMNUMBER<< endl;
return 0;
}
You really need a solution with C-style arrays?
Or a solution with standard containers is good for you?
In this second case (that I suggest) I propose the following example
--- modified to load and print firstNum---
#include <vector>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <stdexcept>
int main ()
{
std::ifstream fin("input.txt", std::ios::in);
int firstNum;
int unused;
unsigned dimV;
if ( ! (fin >> firstNum >> dimV) )
throw std::runtime_error("error reading dimension");
std::vector<int> a(dimV);
std::vector<int> b(dimV);
std::cout << "firstNum is " << firstNum << std::endl;
for ( unsigned i = 0U ; i < dimV ; ++i )
if ( ! (fin >> unused >> a[i] >> b[i]) )
throw std::runtime_error("error reading dimension");
for ( unsigned i = 0U ; i < dimV ; ++i )
std::cout << "-- " << a[i] << ", " << b[i] << std::endl;
return EXIT_SUCCESS;
}
The output
firstNum is 10
-- 5, 67
-- 8, 46
-- 14, 23
If the file remain consistent with the format you gave above and you do not reach the limit of the array, I think this will solve your problem.
int main(int argc, const char * argv[])
{
ifstream fin("input.txt", ios::in);
int A[N];
int B[N];
//get first num and size
int first; // not sure what that is for but i guess you know
int arraySize;
fin >> first;
fin >> arraySize;
int id;
int aData;
int bData;
int i = 0;
while(fin >> id >> aData >> bData)
{
A[i] = aData;
B[i] = bData;
i++;
}
return 0;
}

Representing a User Entered String Diagonally

I am currently a bit stuck. I need to write a program in c++ that allows a user to enter a string (any length with any amount of spaces) and the program then need's to represent this diagonally. I can get it to work but only for the first word and not for any word's entered after the first word. Below you can find my code.
Thanks People!
#include <iostream>
#include <string>
using namespace std;
int main()
{
string strHello;
cin >> strHello;
for(int k = 0; k < strHello.length(); k++)
{
for (int x = 0; x <= k; x++)
{
if (k==x)
cout << strHello.at(x);
else
cout << " ";
}
cout << '\n';
}
return 0;
}
Yes the problem is as others have mentioned, that >> operator stops reading at the first white space character found, so std::getline() does the job, and aditionally you don't need the nested loops, take a look at this
#include <iostream>
#include <string>
using namespace std;
int
main(void)
{
string text;
string spaces;
getline(cin, text);
for (int k = 0 ; k < text.length() ; ++k)
cout << (spaces += ' ') << text.at(k) << endl;
return 0;
}
The problem is in your input, not your output. The problem is that you only call
cin >> strHello;
once. This reads in only the first sequence of non-white-space characters that are delimited by any amount of {white-space, begin of input, end of input}. So, your program will only read in the first such sequence of any input and discards any white space in the input.
Use getline, e.g
std::getline(cin, strHello);
cin will read only the first string it see before white space. e.g. "hello world" will have only hello in strHello.
cin >> will break up the input string at whitespace characters. You should use getline() instead.
getline(cin,strHello);
Here is a program that I think will help:
#include <iostream>
#include <string>
#define MAX_LEN 100
using namespace std;
int main()
{
char strHello[MAX_LEN] = { 0 };
cout << "Enter a string";
cin.getline(strHello, MAX_LEN);
for (int k = 0; k < sizeof(strHello); k++){
for (int x = 0; x <= k; x++){
if (k == x)
cout << strHello[x];
else
cout << " ";
}
cout << '\n';
}
return 0;
}

reading row from text file into two vectors c++

I am trying to read the two words "kelly 1000" in the text file "players", into vectors players and balances respectively. Don't know why it's not working?
string name = "kelly";
int main()
{
int num =0;
vector<string> players;
vector<int> balances;
ifstream input_file("players.txt");
while(!input_file.eof())
{
input_file >> players[num];
input_file >> balances[num];
num++;
}
for(size_t i = 0; i=players.size(); i++)
{
if(name==players[i])
cout << "Welcome " << name << ", your current balance is " << balances[i] << "$." << endl;
else
break;
}
With operator[] you can only access existing elements. Going out of bounds invokes undefined behaviour. Your vectors are empty and you need to use push_back method to add elements to them.
Second problem is while (!file.eof()) anti-pattern. It'll typicaly loop one to many times because the read of last record doesn't neccesarily trigger eof. When reading from streams, always check whether input succeeded before you make use of values read. That's typicaly done by using operator>> inside loop condition.
string temp_s;
int temp_i;
while (input_file >> temp_s >> temp_i) {
players.push_back(temp_s);
balances.push_back(temp_i);
}
This way the loop stops if operator>> fails.
//Hope this is something you want dear.Enjoy
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
string name = "kelly";
int main()
{
int num =0;
string tempname;
int tempbalance;
vector<string> players;
vector<int> balances;
ifstream input_file("players.txt");
while(!input_file.eof())
{ input_file>>tempname;
input_file>>tempbalance;
players.push_back(tempname);
balances.push_back(tempbalance);
}
for(size_t i = 0; i<players.size(); i++)
{
if(name==players.at(i))
cout<< "Welcome " << name << ", your current balance is " << balances.at(i)<< "$." << endl;
}
return 0;
}