Add integers to array using cin simultaneously in C++ [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Hellow guys i want to add nine integers to array at once time without pressing enter key in run time. please guys tell me how to add nine integers to array simultaneously in C++.
Thanks!

If you want to process each integer value right after its input in console is complete (e.g. in that a blank indicates that the next integer value shall begin), you are in a bad position.
The reason is that terminal input (beyond of what your C++ program can influence) often is buffered, and even cin might not receive any character until Enter or EOF is pressed in the terminal.
There may exist workarounds like conio.h or ncurses, but the are not standard and probably not worth the effort in your situation unless you really need to implement integer scanning for a production environment tightly connected to console input.
Try it out and compare input taken directly from console to input from a stream that is already "filled" with enough input:
int main() {
stringstream ss("12 34 56 78 90 10 11 12 13");
//istream &in = ss; // would output each integer immediately.
istream &in = cin; // will probably wait for enter before processing begins.
int value = 0;
for (int i=0; i<9; i++) {
if (! (in >> value))
break;
cout << value << "; ";
}
}

Related

How to organize infinite loop with symbols analysis in it? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I need to organize infinite loop with symbol analysis in it. In C I used fgets(buf, N, stdin), suppose buf is buf[10]. User could type string of any length and I could analyze it by breaking down the input and examining parts of length 10. How can I implement this in C++ without using C libraries. Sorry for my English if you can't understand what I mean
In C++ you should std::cin to read from standard input.
// #include <iostream>
do
{
char buf[10]{}; // create array of 10 bytes filled with zeros.
std::cin.read(buf, 10); // read 10 bytes
// at this point you should check if std::cin.read succeeded.
// otherwise you will be reading zeros.
std::streamsize numRead = std::cin.gcount(); // obtain number of read bytes.
std::cout << numRead << " " << buf << std::endl; // some printing.
}while(std::cin);

Reading from 3 column txt file to different arrays [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I want to read a three column and N row txt file to three different arrays:
int N=100;
double x[N],
y[N],
z[N];
ifstream reading;
reading.open("reading.txt");
reading.close();
What should I write in the empty region? x[j], y[j], z[j] should be element in j'th row and first, second and third column respectively.
Once you get the input file stream, it will be similar to reading from a standard input.
As a hint I can say, what about reading every integer and then store them appropriately. For example,
1 2 3
4 5 6
7 8 9
Now you read everything like this
while (redaing>> num) {
// here you would know whether you are reading the first number
// or second number or third.
// x[xi] = num or y[yi]=num or z[zi]=num
}
Also you need to do something before you start reading from a file using the input file stream.
Have this check to make the program more safe.
if (!reading) {
cerr << "Unable to open file reading.txt";
exit(1); // call system to stop
}
A solution would be like this:
int xi=0,yi=0,zi=0,iter=0;
while(redaing >>num){
if(iter%3==0)x[xi++]=num;
else if(iter%3 ==1)y[yi++]=num;
else
z[zi++]=num;
iter++;
}
More succintly as pointed by user4581301
while(redaing >>x[xi++]>>y[yi++]>>z[zi++]){
//..do some work if you need to.
}
Also another from comment to limit the 100 line reading is [From comment of user4581301]
int index = 0;
while(index < 100 && redaing >>x[index]>>y[index]>>z[index] ){
index++;
}
A better solution:
vector<int> x,y,z;
int a,b,c;
while(reading>>a>>b>>c){
x.push_back(a);
y.push_back(b);
z.push_back(c);
//..do some work if you need to.
}
I'm kind of confused on the wording of your question could you try and reword It? Also if you want to read to the nth row I would use a while loop with the condition being while not end of file. Also you may consider using a vector since you don't know how large of an array you want to create.
A trivial way is
Read the file line by line using getline().
Get the line into an istringstream.
Use istringstream as any istream like cin, it will only contain one line of text.
I would suggest you to search for these terms on some website like www.cppreference.com if you don't know them.

C++ Xcode won't run my for loop (very short) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I want to continue reading Stroustrup PPUC++, but I'm stuck! I wrote a BleepOutTheBadWords program a few days ago and it worked. I tried to write the program with my younger brother a few days ago and I failed. This is essentially a program I wrote to figure out what is going wrong. It is not printing out each word in the "sentence" vector.
#include <iostream>
#include "std_lib_facilities.h" // Stroustrup header file
using namespace std;
int main()
{
cout << "Write a sentence." << endl;
vector<string> sentence;
// Put user input into "sentence" vector
for (string word; cin >> word; )
sentence.push_back(word);
// Print each word in "sentence" vector
for (int i = 0; i < sentence.size(); ++i)
cout << sentence[i] << endl;
// Keep window open and return 0 to show program succeeded
keep_window_open();
return 0;
}
The answer is going to be obvious. Please just state the obvious if you are so kind. I looked through the suggested readings on two different pages before posting this.
XCode won't run my for loop
Your loop is running. The thing that you missed is how to terminate the loop.
for (string word; cin >> word; )
This loop will terminate when cin >> word evaluates to false. Normally, i.e. without an error condition, it will evaluate to false when your input is finished. The exact process to signal an end of stream, or EOF, is platform dependent. If you are running this program on OSX then the most common way to signal EOF is to hit Ctrl + D button, unless you changed the default configuration of your keyboard. Once you signal EOF this input loop will terminate and you will be able to see the output.
I'm pretty much sure that Stroustrup discussed this on his book (though I can not refer to an exact page number). However "Chapter 10: Input and Output Streams" of his books covers these things in detail.

Making a password type program that needs to accept letter and number combinations? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am making a shopping list program. For this program, I need to be able to type in a user input that accepts both number (1564, 121,1, etc) and word (hello, goodbye, etc) combinations. The program reads numbers just fine, but it cannot process words. Thank you in advance. The part of the code I am stuck with is below:
int code, option, count = 0;
double quantity, price, cost;
string description;
cin >> code;
while ((code != 123456789) && (count < 2))
{
cout << "Incorrect code, try again \n";
cin >> code;
count++;
if (count == 2)
{
cout << "max # of tries reached. Goodbye. \n";
system("pause");
}
}
Your code variable is now an int. If you wanted that to be a string, declare it so: std::string code;. Note that you might need to #include <string> in the very beginning. Also, if you want to compare it with numbers, either you call something like atoi() (string has .cstr()), or better yet, you might just compare it with "123456789". HTH.

user enters String instead of Int [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
We have tried to search this problem but we haven't found any answers. If The user inputs a string variable when the system requires a integer how do you evade the problem with out using a while loop?
{
int grade_var=0,grade_1=0,sum=0;
cout<<"Enter the number of grades you have:\t";
cin>>grade_var;
for(int i=1;i<=grade_var;i++)
I don't wish to do a while loop for my program has a lot of integer insertions and want to know an easier way to correct rather than while loops?
While loops are generally the way to go.
However, to keep the code clean, you may want to consider putting said while loop into a helper function, so you can just call PollForIntegerInput(string prompt) from anywhere in your code, and then handle that input in one place. There is almost never a reason you should be duplicating an input loop like that.
As for a truly nonlooping answer, I have none.
Calling operator>> on a stream returns the stream itself, which can be converted to bool to check if the stream is in a good state. If a bad extraction happens, the stream is not in a good state. So you can do something like this:
if (cin >> grade_var)
This will check that it was successful. You can just negate the condition to find it if it wasn't successful. How you handle this condition is up to. Maybe you'll return early on failure. If you want to reprompt the user for correct input, however, you'll need a loop.
It's not too clear what your problem is, but...
It's almost always poor design to input the number of data
points which will follow. If you expect a series of int, for
example:
std::vector<int> grades;
int grade;
while ( std::cin >> grade ) {
grades.push_back( grade );
}
It doesn't get much simpler.
If you do want to insist on an exact number of input, outputting
an error when the user inputs something incorrect, the usual
pattern would be:
std::vector<int> grades;
while ( grades.size() != targetNumber ) {
int grade;
while ( !(std::cin >> grade) ) {
std::cout << "Integer wanted" << std::endl;
std::cin.clear();
std::cin.ignore( INT_MAX, '\n' );
}
grades.push_back( grade );
}
Still no for. (In fact, for loops with input are very, very
rare.)