I have two files, and I am supposed to input both of them into arrays.
One of them is:
2
3
4
5
7
8
The second one is
2
4
5
6
7
8
2
3
4
5
7
8
(it's much longer, but it doesn't matter). I need to have one array with the first 6 numbers, and then I am supposed to check if first six numbers from the second file are the same as the numbers in the second array, same with the next six numbers and so on (like checking for a lottery winner).
I guess that I am supposed to load numbers from one file into multiple arrays, but I have no idea how to do it, and I can't find it anywhere.
The code for the first array that I have so far is:
#include<iostream>
#include<fstream>
using namespace std;
int main(){
int numbers[6];
int count = 0;
ifstream inputFile;
inputFile.open("Numbers.txt");
while (count < 20 && inputFile >> numbers[6]){
count++;
inputFile.close();
for (count=0; count < 20; count++)
cout << numbers[count];}
return 0;
}
Another problem is that instead of displaying the numbers correctly, it displays "-858993460" 6 times - even though my code is basically copied from a book...
What is wrong with my code, and how do I input the second file?
Your main problem is doing stuff inside your loop that should not be there. The loop is supposed to run once for each value it reads in from the file. After it is finished is when you should close the file and print the results.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int numbers[6];
int count = 0;
ifstream inputFile;
inputFile.open("Numbers.txt");
if(!inputFile.is_open()) // always check for errors
{
std::cerr << "ERROR opening input file:" << std::endl;
return 1; // error
}
// make sure count < 6 so you don't overflow your array
while(count < 6 && inputFile >> numbers[count])
{
count++;
// inputFile.close(); // don't close the file yet!!
//for(count = 0; count < 20; count++) // don't output yet!!
// cout << numbers[count];
}
// now close your file and output what you have
inputFile.close();
for(count = 0; count < 6 /* not 20!! */; count++) // don't output yet!!
cout << numbers[count] << '\n';
return 0;
}
This is an example of reading numbers from your first file. This example can be added to, to read numbers from your second file and compare them with the numbers read from the first file.
Updated:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int numbers[6];
int count = 0;
ifstream inputFile;
inputFile.open("Numbers.txt");
// get each number from the file until the end-of-file bit
// is retrieved.
while ((inputFile >> numbers[count]) && (count < 6)){
// iterate count by one
count++;
}
inputFile.close();
// run through the array of numbers and ouput each index
for(int i = 0; i < 6; i++) {
cout << "numbers[" << i << "] = " << numbers[i] << "\n";
}
}
Input: "Numbers.txt"
2
3
4
5
7
8
Output: cout
numbers[0] = 2
numbers[1] = 3
numbers[2] = 4
numbers[3] = 5
numbers[4] = 7
numbers[5] = 8
Update:
Faulty Input:
d
3
4
5
7
8
Output
numbers[0] = 0
numbers[1] = 0
numbers[2] = -1527900896
numbers[3] = 32627
numbers[4] = -1527901752
numbers[5] = 32627
Related
I need to write a program that takes input from the user and multiplies it by numbers: 3, 5, 7, and 9. Here is my code:
#include <iostream>
int main()
{
int N;
std::cout << "Input a number: ";
std::cin >> N;
int limit = 9;
for(int i = 3; i <= limit; ++i)
{
if(i % 2 != 0) // if odd
{
N = N * i;
std::cout << N << std::endl;
}
}
return 0;
}
When I output this code, it displays:
Input a number: 1
3
15
105
945
However, what I am aiming for is this:
Input a number: 1
3
5
7
9
Any help would be greatly appreciated.
You over write your variable N at N = N * i. You should add a second variable to output your result and not overwrite your input.
Tip: You increment your loop by just one with ++i. If you replace that with i+=2 you only loop over the desired multiplication numbers. At this point you can also leave out the if statement.
I'm beginning with C++. The question is: to write a program to input 20 natural numbers and output the total number of odd numbers inputted using while loop.
Although the logic behind this is quite simple, i.e. to check whether the number is divisible by 2 or not. If no, then it is an odd number.
But, what bothers me is, do I have to specifically assign 20 variables for the user to input 20 numbers?
So, instead of writing cin>>a>>b>>c>>d>>.. 20 variables, can something be done to reduce all this calling of 20 variables, and in cases like accepting 50 numbers?
Q. Count total no of odd integer.
A.
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
int n,odd=0;
cout<<"Number of input's\n";
cin>>n;
while(n-->0)
{
int y;
cin>>y;
if(y &1)
{
odd+=1;
}
}
cout<<"Odd numbers are "<<odd;
return 0;
}
You can process the input number one by one.
int i = 0; // variable for loop control
int num_of_odds = 0; // variable for output
while (i < 20) {
int a;
cin >> a;
if (a % 2 == 1) num_of_odds++;
i++;
}
cout << "there are " << num_of_odds << " odd number(s)." << endl;
If you do really want to save all the input numbers, you can use an array.
int i = 0; // variable for loop control
int a[20]; // array to store all the numbers
int num_of_odds = 0; // variable for output
while (i < 20) {
cin >> a[i];
i++;
}
i = 0;
while (i < 20) {
if (a[i] % 2 == 1) num_of_odds++;
i++;
}
cout << "there are " << num_of_odds << " odd number(s)." << endl;
Actually, you can also combine the two while-loop just like the first example.
Take one input and then process it and then after take another intput and so on.
int n= 20; // number of input
int oddnum= 0; //number of odd number
int input;
for (int i = 0; i < n; i ++){
cin >> input;
if (input % 2 == 1) oddnum++;
}
cout << "Number of odd numbers :"<<oddnum << "\n";
The program output Should be:
The numbers are: 101 102 103 104 105 106 107 108 108 110
But my output is:
The numbers are: 0 0 0 0 0 0 0 0 1606416272 32767
This is my code:
// This program reads data from a file into an array.
#include <iostream>
#include <fstream> // To use ifstream
using namespace std;
int main()
{
const int ARRAY_SIZE = 10; // Array size
int numbers[ARRAY_SIZE]; // Array number with 10 elements
int count = 0; // Loop counter variable
ifstream inputFile; // Input file stream object
// Open the file.
inputFile.open("TenNumbers.rtf");
// Read the numbers from the file into the array.
while (count < ARRAY_SIZE && inputFile >> numbers[count]){
count++;
}
// Close the file.
inputFile.close();
// Display the numbers read:
cout << "The numbers are: ";
for (count = 0; count < ARRAY_SIZE; count++){
cout << numbers[count] << " ";
}
cout << endl;
return 0;
}
This is the contents of the TenNumbers.rtf file I'm reading the data from:
101
102
103
104
105
106
107
108
109
110
UPDATE 1:
I tried using txt file but the results are similar.
The numbers are: 0 0 0 0 0 0 0 0 1573448712 32767
UPDATE 2:
I found where the issue was. After running if (inputFile.good()) I found out the file was not getting opened.
Hi I have compiled your code, with the .txt it runs well, without gives the strage numbers that you see.
So probably you are opening a file that does not exists, or can not be red.
// This program reads data from a file into an array.
#include <iostream>
#include <fstream> // To use ifstream
#include <vector>
using namespace std;
int main()
{
std::vector<int> numbers;
ifstream inputFile("c.txt"); // Input file stream object
// Check if exists and then open the file.
if (inputFile.good()) {
// Push items into a vector
int current_number = 0;
while (inputFile >> current_number){
numbers.push_back(current_number);
}
// Close the file.
inputFile.close();
// Display the numbers read:
cout << "The numbers are: ";
for (int count = 0; count < numbers.size(); count++){
cout << numbers[count] << " ";
}
cout << endl;
}else {
cout << "Error!";
_exit(0);
}
return 0;
}
This snippet checks if the file exists, raises an error if not, and uses a vector(more suitable in c++)
Your file name has rtf as suffix. Does it contain any RTF info in it?
The error that I see in your code is that you are assuming ARRAY_SIZE number of ints were successfully read when you are printing the numbers.
Use:
// Display the numbers read:
cout << "Number of ints read: " << count << std::endl;
cout << "The numbers are: ";
for (int i = 0; i < count; i++){
cout << numbers[i] << " ";
}
This will, most likely, reveal any problems in reading the data.
ARRAY_SIZE is the number of ints you allocated in the array; that is, it is the max number of ints.
count is the actual number of ints read from the file. So your final loop should go up to count since that is the number of actual data. So the loop that prints your data should be:
int i;
for (i = 0; i < count; ++i)
cout << numbers[count] << " ";
Or you can walk a pointer:
int *start;
for (start = numbers; (numbers - start) < count; ++numbers)
cout << *numbers << " ";
Also, I think the file extension should be "txt" rather than "rtf", but that doesn't make a difference.
An RTF file is not just plain text (it's surrounded by markup) and the character encoding may differ, thus resulting in wrong interpretation of the numbers.
So, in your reading loop:
// Read the numbers from the file into the array.
while (count < ARRAY_SIZE && inputFile >> numbers[count]){
count++;
}
the input stream inputFile by default is skipping white spaces which in your case could be encoded differently, thereby skipped or messed up in some way.
Note: Try and add a test line that prints the read number before you store it in the array.
I had met this problem before too. I copy the content into a new file and save as different name. Then it will be fine when run it again.
This question already has answers here:
Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?
(5 answers)
Closed 8 years ago.
My program is all running fine except that it is reading a seemingly random seven-digit number at the end of the file to add an additional number to the file and I have not been able to figure out why. I was able to determine that it has something to do with the first while() loop.
I have tried everything I can think of and one thing I have noticed is that when I change the global variable to the number of numbers I know are in the file (12) it will work perfectly. However, I am suppose to do this so that I do not know exactly how many numbers are in the file.
What the output in the new file is suppose to look like but with the extra number:
8
10
12
17
25
36
47
62
62
65
87
89
2972880 //However this last seven digit number is not suppose to be there...here is the code...
#include <iostream>
#include <fstream>
using namespace std;
const int SIZE = 256;
int main(void)
{
int getNumbers[SIZE];
ofstream outFile;
ifstream inFile;
bool success;
int count = 0,
total = 0,
add = 1;
int num;
inFile.open("numbers.txt");
if (inFile.is_open())
{
cout << "File successfully read." << endl;
}
while (count < (total + add) && !inFile.eof())
{
inFile >> getNumbers[count];
total += add;
count++;
}
int grandTotal = (total - 1);
do
{
success = false;
for (int i = 0; i < grandTotal; i++)
{
if (getNumbers[i] > getNumbers[i + 1])
{
num = getNumbers[i];
getNumbers[i] = getNumbers[i + 1];
getNumbers[i + 1] = num;
success = true;
}
}
grandTotal--;
} while (success);
inFile.close();
outFile.open("sorted.txt");
if (outFile.is_open())
{
cout << "File successfully opened." << endl;
}
int index = 0;
while (index < total)
{
outFile << getNumbers[index]
<< " \n";
index++;
}
outFile.close();
return 0;
}
As #Galik pointed out, you shouldn't check for eof() in a loop condition, because it will always give you one garbage data point at the end. Move the read into the loop condition.
while (count < (total + add) && inFile >> getNumbers[count])
{
total += add;
count++;
}
This question already has answers here:
Why getline skips first line?
(3 answers)
Closed 9 years ago.
In this code ,getline is not working for i =1 .but for i = 0 it is working completely fine.
What I should do to repeatedly work with the getline function.This code takes a number and checks its divisibility."numb" is taken to store the number.for i = 0 all the calcultions are just fine but when it goes for the 2nd turn ,don't know what happens but cin.getline doesn't work.
#include <iostream>
#include <cstring>
#include <iomanip>
#include <cstdio>
#include <cstdlib>
#define MAX 1050
using namespace std ;
int call_div (char *num ,long div)
{
int len =strlen (num) ;
int now ;
long extra ;
for (now = 0,extra=0; now < len; now += 1)
{
extra = extra *10 + (num [now] -'0') ;
extra = extra %div ;
}
return extra ;
}
int main (int argc, char const* argv[])
{
int testcase,numbers ,flag =0;
char numb[MAX] ;
cin >> testcase ;
getchar() ;
for (int i = 0; i < testcase; i += 1)
{
cout << i << endl ;
int div[14] ;
cin.getline(numb) ; // i= 0 ,it works fine ,i=1 ,it doesn't work
cin >> numbers ;
for (int j = 0; j < numbers; j += 1)
{
cin >> div[j] ;
}
for (int k = 0; k < numbers; k += 1)
{
// cout << div[k]<< ' ' << call_div (numb,div[k]) << endl ;
if (call_div (numb,div[k])==0)
{
flag = 1 ;
}
else {
flag = 0 ;
break;
}
}
if (flag==0 )
{
cout << "simple"<< endl ;
}
else
cout << "wonderful" << endl ;
}
return 0;
}
I think Your input may look like
something
3 1 2 3
some other thing
4 1 2 3 4
First time You read "something" with getline(). Then your algorithm reads the 3 as numbers, and then the three number followed by that one. And here reading stops. Next time You call getline(), it will continue reading until it reaches the first '\n' character. So it will not read "some other thing" when You want it.
Now I can not try it, but I think it will work fine with an extra "dumb" getline() after the loop that fills the div array.