C++ :: Reading Unknown Number Of Inputs And Adding Them In Vector
Jan 16, 2013
Consider the following piece of Code:
int ReadNumbers() {
int num;
vector<int> x;
cout << "Enter Numbers" << '
[Code] ....
The while loop is expected to terminate when the user provides an Invalid Input. But this while loop behaves unexpectedly when the user provides a 'Newline' input (by pressing Enter) and becomes an infinite loop. How can I prevent this from happening? Also I've heard that expecting invalid inputs isn't good code design. Is this true? If yes, then how can I solve my question without expecting Invalid Inputs?
View 10 Replies
ADVERTISEMENT
Mar 1, 2015
I have a file with such a format:
string string 8 7 2
string string 7 12 19 -4
string string 1
As you can see I don't know how many numbers there are at the end. I have this code now:
while(!in.eof()) {
kr = 0;
getline(in, pavard, ','); getline(in, vard, ','); getline(in, gr, ',');
while(in.peek()) {
in >> k;
kr += k;
}
in.ignore();
}
in.close();
I tried various combinations with peek() function, but nothing worked.
View 2 Replies
View Related
Jan 23, 2013
I want my program to be able to read text files in the format:
number number
number number
number number...
and so on, so there are two columns of values. The problem I'm having is, there are a lot of numbers in the file, and it can vary. The program needs to read the numbers, put one column into one array, and the other in another, perform some operations on it all, and eventually pop out two different arrays. In other words, after I've got these arrays, I don't need them for much longer. I was hoping I could dynamically allocated some arrays to store the numbers and just free them as soon as I'm done with them.
If the file wasn't of such variable size or if it was guaranteed to be under a certain number of variables, I would have used:
Code:
while ( fscanf(input, "%lf %lf
", &col_1[], &col_2[]) == 2 )
{
no_rows++;
}
The problem is I want to allocate "no_rows" as the array size, which I don't have until after I have read the file.
View 9 Replies
View Related
Oct 10, 2014
I want to read a string of unknown length from stdin. I tried to follow the approach from this link.
[URL]....
My code is like this:
Code:
#include <iostream>
#include <string>
using namespace std;
int n;
cin >> n;
cout << "The value of n is " << n << endl;
string str;
getline(cin, str);
cout << "The entereed string is " << str << endl;
What I have noticed is that if I take integer input from cin (cin >> n in the above code before getline, the control does not stop on getline to take str as input from the console. If I don't do (cin >> n) before getline then the control stops on getline and takes the string as input.
What is the best way to read from console multiple strings of unknown length in combination with the integers?
View 1 Replies
View Related
Dec 2, 2012
i dont usually write console programs, and i cant seem to find out how one parses an unknown number of arguments with cin.
the program receives an unknown amount of integers in stdin, and i need to parse them withouth hanging.
Unfortunately, stdin is a async. stream and blocks, if it doesnt find any integers left.
I cant use peek() or seek() either, as both are async, too, (which makes me wonder what their exact use is?).
View 3 Replies
View Related
Jan 23, 2014
I am beginner at C and I was working on a program where I have to read in a line such as Digit, String, Float. The string can have any amount of spaces between it. and each input is separated by a space character.
The input is of the format:
10000000000 hello my n ame is 30.2
So I used fgets(x,100,stdin) to read the line in.
So I need to read that line into an int, array, and float.. so I was thinking of using this:
sscanf(x, "%d %[^/n] %f", &number, &username, &numberfloat);
Now, obviously I can't use the /n to read in the username with spaces because I need to read the 30.2 into a float variable.
View 5 Replies
View Related
May 1, 2013
So I'm making setTimeout and setInterval functions.
I have this remember function (that is part of Timing class) which takes a function pointer and a void pointer, which are remembered in that object.
Another (timing) function of that object is called in every loop of the program and when specific time passes that function calls the remembered function whit the remembered void pointer as argument.
The problem is that the functions that need to be called require unknown multiple parameters, so what I need to do is make a new class that will store the needed arguments. I make the function that needs to be called and that storage object and pass pointers to them to my remember function, when the remembered function is called it stores the data from storage object in new variables and dose it's thing.
View 3 Replies
View Related
Feb 21, 2014
I'm trying to create a program that allows the user to enter an unknown number of income and expense amounts. The program has to us see a while loop and display the income total, expense total, and total profit or loss. I've got it really close, but I'm doing the loop wrong. It counts the sentinel value (-1) towards the total, instead of just ending like it is supposed to.
#include <iostream>
using namespace std;
int main() {
//declare variables
double incomeInput;
double expenseInput;
double incomeTotal=0;
double expenseTotal=0;
[code]....
View 5 Replies
View Related
Sep 10, 2013
I want to program a program that produces a random number between 1-10, then if the number is correct, says like HEY GOOD JOB and if its not says try AGAIN! also, at any point the user can quit by typing in X.
I know that I can use stuff like cout << "Hey put in a guess now" to prompt the user but I dont know how to accept inputs.
For example, how do I use scanf to do this?
I know that if I use scanf, it takes in a value, but where the heck does it store it?
eg. scanf(%s,guess);
Is that valid? I get an invalid expression error when trying to use that in C++.
View 3 Replies
View Related
Jan 11, 2015
I am fairly new to C++ and I am trying to write a code that determines whether a number which the user inputs is prime or not. I have the code, but when I run it all it actually does is report odd numbers as prime and even numbers as not prime.
#include <iostream>
using namespace std;
//declaring variables//
int i;
int num;
[Code] ....
View 7 Replies
View Related
Apr 10, 2014
I have a basic question regarding 2d vectors. The following code makes a 2d vector and fills it with a matrix of integers. The vector tempVector3 gets added as a new row to the matrix. But what if I wanted to add the tempVector3 as a new column instead. How would this be done in the simplest way?
#include<iostream>
#include<vector>
int main(){
std::vector<std::vector<int>> numbers;
std::vector<int> tempVector1;
tempVector1.push_back(2);
[Code] ....
View 5 Replies
View Related
Feb 7, 2015
I am writing a program that deals with 2d arrays. The program inputs the number of rows and columns and asks for the entries. When the program run and compiles it works perfectly until it outputs then it gives me a warning.
Here is my code:
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int row1=0,col1=0,i,j;
//int a[row1][col1];
int** a= new int*[row1];
[Code]...
I am learning how to do this before I can move on so it can read a text file of numbers.
Also I am having problems with ////delete [] a[];///// I took it out because it made my code compile and run but when I add it in, it gives me an error:
matrixtesting.cpp|56|error: expected primary-expression before ']' token|
I know this expression is suppose to deallocate the array.
View 7 Replies
View Related
Apr 9, 2014
write a c++ program that reads an unknown number of integer values and then print count, sum and average of odd values, even values, positive values, negative values!!
View 1 Replies
View Related
Oct 10, 2013
I have a vector of structs.
struct myStruct{
string text;
int num;
};
vector<myStruct> foo;
And I am attempting to print the text followed by a space, then the number. Like so:
foobar 5
But when trying to print my vector using
ofstream outputFile;
outputFile.open ("file.txt");
for(int i = 0; i < foo.size(); i++) {
outputFile << foo[x].text << " " << foo[x].num << endl;
}
It prints like
foobar
5
moretext
8
With an extra newline and space. How to get rid of it and print it on the same line.
I have checked that text does not include new line character at the end. Also, it seems to print correctly using cout, but not print correctly to output file...
View 1 Replies
View Related
Jan 11, 2014
I have created an error message if the user inputs the wrong selection number
if (choices < 1 || choices > 5)
{
cout << "
Please Enter a number between 1-5
";
}
How would i create a error message if the user inputs letters/words instead of a number.
View 5 Replies
View Related
Feb 1, 2013
I am adding int type into vector called "vi" several times like this.
std::vector<int> vi;
void addFunc(int *a, int cnt) {
vi.erase(vi.begin(), vi.end());
vi.clear();
for(int i=0; i<cnt; i++)
vi.push_back(a[i]);
}
and I call the addfunc N times every sec.
And sometimes it has runtime error on vi.push_back line.
(called stack says "_CrtIsValidHeapPointer")
View 5 Replies
View Related
Oct 10, 2013
how to add a list of information from a file to a vector of a class. Here is my code:
Champion_Info.h
#ifndef CHAMPION_INFO_H_INCLUDED
#define CHAMPION_INFO_H_INCLUDED
#include <vector>
#include <string>
[Code].....
View 6 Replies
View Related
Jan 30, 2013
How would I add my own function to the vector class?
View 3 Replies
View Related
Jun 1, 2014
I've been trying to write my homework assignment (a list of countries, their codes and their capitals) and I've done most of it but I'm stuck at this: I have to open a file, read it and if there are data, add them to the list. So far I've created an element of the structure, queue list, printed the list on the screen and freed the memory. I thought that for reading the file and adding the data I could first open the file (of course) with fopen and after that use a for loop (i=0;i=!EOF;i++) to scan the whole file and fscanf(fp,"%s",result->country),etc in the loop to add the data to the structure of the element and finally insert that element to the queue list. However, when I try to do these operations, I only get to writing the name of the file and the program crashes.
Code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct List {
char country[20];
char code[5];
char capital[20];
struct List*next;
[Code] .....
View 1 Replies
View Related
Apr 20, 2014
I'm having a problem filling a vector from a file. Basically, it is adding an empty element at the end. I'm new to Qt and haven't worked with file streams much so how to stop the stream before it adds the extra element.
void gui::get_data() {
mileage.clear();
QFile file(file_label->text() + ".txt");
QTextStream in(& file);
float m;
float g;
QString d;
[Code] ....
But, if I add another element to the vector and write that the file look like this.
//file after adding element
132654 0 02132014
132654 0 02132014
0 0
132998 22 02202014
I have it set to append at the moment so that is why the first line is repeated. I figure the problem is with if(in.atEnd()). I could fix it by deleting the last element right after adding it, but that seems like more of a hack than anything else.
View 3 Replies
View Related
Feb 6, 2014
In this program what i'm doing is to search for a number when the vector is in order, and count how many times that number appears, the problem is that count how many times the number does not appear, but when its appear the program stays in an "standby mode" and the cursor does not move.
int buscarNumOrdenado (int x [MAX]) //MAX is the define {
int num,d, LimiteInferior, LimiteSuperior,mitad;
d=0;
LimiteInferior = 0;
LimiteSuperior = MAX-1;
[Code] ....
View 2 Replies
View Related
May 1, 2014
I have this program thats supposed to add a number to all of its precedents. so if the input was 5, it would add 5+4+3+2+1 and give 15. I know i can implement this in a billion different way and it wouldnt be much of a challenge, but im really confused as to why this isnt working. It gives a large negative number when i run it.
#include <iostream>
using namespace std;
int main() {
int b;
cout<<"Enter a number, ill return that number plus every number below it: ";
[Code] ....
View 9 Replies
View Related
Jun 28, 2013
When i run the program i want to add a big integer number into an int array. How can i do it.i don't want to use for loop.
View 4 Replies
View Related
Dec 10, 2013
When I run the program the first int that is stored in the array keeps changing to -858993460.
#include <iostream>
using namespace std;
int main() {
int i;
int j;
int testScore[5];
int count;
[Code] .....
View 1 Replies
View Related
Feb 22, 2015
I'm having trouble finishing this program. What I'm trying to do is create a class for Rational numbers. Get input from user for denominator and numerator. Store the numbers without a sign, and for the sign store it separately in char. I'm not supposed to use accessor functions. The part that I can't seem to know how to do is use the info that was stored in the addUp function. This function need to add two rational numbers. i need to make this function general enough that it can handle two fractions, or a fraction and a whole number, or two whole numbers. What I already have here is readin function which reads in the numerator and denominator. setnumerator and setdenominator to assign positive values. setsign should get the sign of the fraction. Finally addUp should addUp which I explained before. I have some ideas about writing the tests, but can't seem to know how to implement it to the program. The main program is still empty but all I'm supposed to do there is call the class functions.
Code:
#include <iostream>
using namespace std;
class Rational {
private:
int numerator, denominator;
char sign;
[Code] .....
View 14 Replies
View Related
Jan 26, 2014
My program writes a vector to a file in binary. I want to erase the vector, then read the file to repopulate the vector then display.
Basically I want to erase the RAM memory and be able to use the file as memory. This is my current code but it is not reading the file correctly. I have checked the file to see that the writing part is working.
void read_from_file(vector<Info> &vector)
{fstream file;
file.open("info.dat", ios::binary | ios::in);
if (file.fail())
{
cout<<" FILE DOES NOT EXIST ";
system("pause");
[Code]...
View 7 Replies
View Related