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.
Related
How can I have an output of
Sample Input No.1:
9
Sample Output No.1:
1.2.3.4.5.6.7.8.9
If you input numbers less than or equal to 9, the output should be (1.2.3.4.5.6.7.8.9)
And if you input numbers greater than 9, for example:
Sample Input No.2:
20
Sample Output No.2:
01.02.03.04.05.06.07.08.09.10
11.12.13.14.15.16.17.18.19.20
My code below is for Sample Input & Output No.2. I tried adding another for loop for SAMPLE NO.1 but it still reads Sample No.2 code. What should I do?
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
int a, num;
cin >> num;
if (num > 100 || num <= 1){
cout << "OUT OF RANGE";
}
else {
for (int a = 1; a < num; a++){
cout << setfill('0') << setw(2) << a << ".";
}
cout << num;
}
}
kind of new to programming, don't know much🥲
As a possible solution, you could read the input as a string, then convert it to an integer.
Use the string length as the field width for the setw manipulator.
This should be able to handle values of (theoretically) arbitrary length.
I want to read the data from my input file
70 95 62 88 90 85 75 79 50 80 82 88 81 93 75 78 62 55 89 94 73 82
and store each value in an array. There's more to this particular problem (the other functions are commented out for now) but this is what's really giving me trouble. I looked for hours at the previous question about data and arrays but I can't find where I'm making the mistake.
Here's my code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int SIZE = 22;
int grades[SIZE];
void readData() {
int i = 0;
int grades[i];
string inFileName = "grades.txt";
ifstream inFile;
inFile.open(inFileName.c_str());
if (inFile.is_open())
{
for (i = 0; i < SIZE; i++)
{
inFile >> grades[i];
cout << grades[i] << " ";
}
inFile.close(); // CLose input file
}
else { //Error message
cerr << "Can't find input file " << inFileName << endl;
}
}
/*
double getAverage() {
return 0;
}
void printGradesTable() {
}
void printGradesInRow() {
}
void min () {
int pos = 0;
int minimum = grades[pos];
cout << "Minimum " << minimum << " at position " << pos << endl;
}
void max () {
int pos = 0;
int maximum = grades[pos];
cout << "Maximum " << maximum << " at position " << pos << endl;
}
void sort() {
}
*/
int main ()
{
readData();
return 0;
}
and here's my output:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Thank you for your time.
The issue is that you're declaring a local grades array with a size of 1, hiding the global grades array. Not only that, you are now accessing the array beyond the bounds, since the local grades array can only hold 1 item.
So get rid of the line:
int grades[i];
However, it needs to be mentioned that this:
int i = 0;
int grades[i];
is not valid C++ syntax. You just stumbled into this by mistake, but that code would not compile if compiled using a strict ANSI C++ compiler.
An array in C++ must be declared using a constant expression to denote the number of entries in the array, not a variable. You, by accident, are using a non-standard compiler extension called Variable Length Arrays or VLA's for short.
If this is for a school assignment, do not declare arrays this way (even if you meant to do it), as it is not officially C++. If you want to declare a dynamic array, that is what std::vector is for.
I don't see any issue in reading the file , you have just confused the global vs local variable of grades
You don't need this
int i = 0;
int grades[];
Inside the function readData
#include <string>
using namespace std;
const int SIZE = 22;
int grades[SIZE];
void readData() {
string inFileName = "grades.txt";
ifstream inFile;
inFile.open(inFileName.c_str());
if (inFile.is_open())
{
for (int i = 0; i < SIZE; i++)
{
inFile >> grades[i];
cout << grades[i] << " ";
}
inFile.close(); // CLose input file
}
else { //Error message
cerr << "Can't find input file " << inFileName << endl;
}
}
int main()
{
readData();
return 0;
}
Your original global array grades, of size 22, is replaced by the local array with the same name but of size 0.
(It is not overwritten, just any code using the variable grades, inside the scope that the second one was defined, will read the value of the second grades array, as it has a higher precedence.)
Both inFile >> grades[i]; and cout << grades[i] << " "; should return runtime errors as you are reading beyond their size (It appears that you are not using a strict compiler).
[int grades[i]; would return a compile time error normally as you shouldn't / usually can't initialize a fixed array with a variable]
I think what is happening, instead of your program crashing, is that grades[i] is just returning an anonymous instance of a variable with value 0, hence your output.
The simplest fix to your problem would be to just delete int grades[i].
(Also delete one of the int i = 0's as you don't need that to be defined twice)
Here is the instructions:
Write a program that reads in a text file one word at a time. Store a word into a dynamically created array when it is first encountered. Create a paralle integer array to hold a count of the number of times that each particular word appears in the text file. If the word appears in the text file multiple times, do not add it into your dynamic array, but make sure to increment the corresponding word frequency counter in the parallel integer array. Remove any trailing punctuation from all words before doing any comparisons.
Create and use the following text file containing a quote from Bill Cosby to test your program.
I don't know the key to success, but the key to failure is trying to please everybody.
At the end of your program, generate a report that prints the contents of your two arrays
Here is my Code:
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <cctype>
using namespace std;
int main()
{
ifstream inputFile;
int numWords;
string filename;
string *readInArray = 0;
char testArray[300] = {0};
char *realArray = 0;
const char *s1 = 0;
string word;
int j =1;
int k = 0;
int start =0;
int ending = 0;
char wordHolder[20] = {0};
cout << "Enter the number of words the file contains: ";
cin >> numWords;
readInArray = new string[(2*numWords)-1];
cout << "Enter the filename you wish to read in: ";
cin >> filename;
inputFile.open(filename.c_str());
if (inputFile)
{
cout << "\nHere is the text from the file:\n\n";
for (int i=0; i <= ((2*numWords) -1); i +=2)
{
inputFile >> readInArray[i]; // Store word from file to string array
cout << readInArray[i];
strcat(testArray, readInArray[i].c_str()); // Copy c-string conversion of word
// just read in to c-string
readInArray[j] = " ";
cout << readInArray[j];
strcat(testArray, readInArray[j].c_str()); // This part is for adding spaces in arrays
++j;
}
inputFile.close();
}
else
{
cout << "Could not open file, ending program";
return 0;
}
realArray = new char[strlen(testArray)];
cout << "\n\n";
for(int i=0; i < strlen(testArray); ++i)
{
if (isalpha(testArray[i]) || isspace(testArray[i])) // Is makes another char array equal to
{ // the first one but without any
realArray[k]=testArray[i]; // Punctuation
cout << realArray[k] ;
k++;
}
}
cout << "\n\n";
for (int i=0; i < ((2*numWords) -1); i+=2)
{
while (isalpha(realArray[ending])) // Finds space in char array to stop
{
++ending;
}
cout << "ending: " << ending << " ";
for ( ; start < ending; ++start) // saves the array up to stopping point
{ // into a holder c-string
wordHolder[start] = realArray[start];
}
cout << "start: " << start << " ";
readInArray[i] = string(wordHolder); // Converts holder c-string to string and
cout << readInArray[i] << endl; // assigns to element in original string array
start = ending; // Starts reading where left off
++ending; // Increments ending counter
}
return 0;
}
Output:
Enter the number of words the file contains: 17
Enter the filename you wish to read in: D:/Documents/input.txt
Here is the text from the file:
I don't know the key to sucess, but the key to failure is trying to please everybody.
I dont know the key to sucess but the key to failure is trying to please everybody
ending: 1 start: 1 I
ending: 6 start: 6 I dont
ending: 11 start: 11 I dont know
ending: 15 start: 15 I dont know the
ending: 19 start: 19 I dont know the key
ending: 22 start: 22 I dont know the key to>
ending: 29 start: 29 I dont know the key to sucess
ending: 33 start: 33 I dont know the key to sucess but↕>
My Question:
Something is wrong with the last for-loop, it crashes after I run it. I included the ending and starting variables to maybe help see whats going on. I know there are better ways of doing this problem but the instructor wants it done this way. If you know where I went wrong with the last for-loop any help would be very much appreciated!!
You aren't null-terminating your strings as you go along. You copy the characters correctly, but without null terminators, your loops might go off into the weeds.
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
This is part of a greater code for reading an input file word-for-word, then printing the words in reverse order. It uses a string array called words[] to store, word-by-word, the char strings from an input file earlier in the program:
//print to screen
for (int i = MAXSIZE; i >= 0; i--)
{
cout << words[i] << " ";
}
Test input file contents:
This is my test file. I hope this works.
Output is just "works. " repeating on and on.
Why is the i-- apparently never happening?
EDIT: Everything from my code. I'm on a bit of a time crunch here, to say the least. MAXSIZE=1024 part of lab prompt. Can't use vectors or reverse; seen that all over, but it's off limits for this lab. New to programming, so if you could refrain from being condescending, that'd be great. Just trying to get this to work. The reading input.txt and print to screen bit works fine. Output portion is utter fail and I don't know why. Can someone just tell me why instead of insulting me, thanks?
//Kristen Korz
//CIS 22A
//This program reads an input file and writes the words in reverse order to an output file.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
//create and link input...
ifstream inputFile;
inputFile.open("input.txt");
//...and output files
ofstream outputFile;
outputFile.open("output.txt");
//error message for file open fail
if (inputFile.fail())
cout << "Error opening the file.\n";
//constant for max size
const int MAXSIZE = 1024;
//string array and temporary-use string
string words[MAXSIZE];
string str; //note: variables will be used for output loops too
//read words from input file
for (int i = 0; (inputFile >> str) && (i < MAXSIZE); ++i)
{
words[i] = str;
//for showing in terminal if read correctly
cout << words[i] << " ";
}
inputFile.close();
cout << endl;
//something wrong with for loop resulting in i apparently not updating
for (int i = MAXSIZE; (outputFile << str) && (i >= 0); --i)
{
words[i] = str;
//for showing in terminal if written correctly
cout << words[i] << " ";
}
outputFile.close();
cout << endl;
system("pause");
return 0;
}
For output with i also printed, my cout statements in the for-loops say:
cout << words[i] << " " << i << " ";
Giving terminal output:
This 0 is 1 my 2 test 3 file. 4 I 5 hope 6 this 7 works. 8
works. 1023 works. 1022 works. 1021 (lots of repeats of works. followed by decrementing numbers) works. 3 works. 2 works. 1 works. 0
Your output loop does:
words[i] = str;
for every iteration. str still holds the value of the last string you input, so this sets every member of words to be the same string. Since your last input string was "works", this explains why you output "works" every time.
It should work better if you just remove that line. Also, start from MAXSIZE - 1. The valid indices of the array are 0 through MAXSIZE-1. Your out-of-bounds access causes undefined behaviour, although apparently in this instance it had no effect.
However if your input only has 8 words as you suggest, then outputting 1024 words will give you a lot of blank space. Consider starting the output from where i got up to, instead of MAXSIZE - 1.
At the part marked as not working (the second for loop), str is being read from but it is never changed to anything else in that loop, so it repeats the last word. i is being updated, the problem is that str is not being updated.
The other issue is that you are trying to access an element past the end of the array, as WhozCraig and Velthune discussed in their answers. You need to properly figure out what you want to do with words in your second for loop. This is key. Also, you need to store where the array you read in ends.
Viewing WhozCraig's link, if you have:
const int MAXSIZE = 1024;
string words[MAXSIZE];
for (int i = MAXSIZE; i >= 0; i--) {
cout << words[i] << " ";
}
You have a string that from 0..1023.
Accessing words[1024] is potentially dangerous.
For iterate correctly your string do:
for (int i = MAXSIZE - 1; i >= 0; --i) {
cout << words[i] << " ";
}
By the way, when you fill words, add a control:
for (int i = 0; (inputFile >> str) && (i < MAXSIZE); ++i)) {
if(str.size() <= MAXSIZE) {
words[i] = str;
}
}
update
Be sure that your string in file:
"This is my test file. I hope this works. "
doesn't end with a space. To be sure, test adding "EOF" to your string:
"This is my test file. I hope this works.EOF"
Other, do your loop in this way:
int i = 0;
while(inputFile.good() && i < MAXSIZE) {
std::string word << inputFile;
if(!word.empty())
words[i] = str;
//for showing in terminal if read correctly
cout << words[i] << " ";
}
The problem why you get a lot of "works" here is:
After this piece of codes:
//read words from input file
for (int i = 0; (inputFile >> str) && (i < MAXSIZE); ++i)
{
words[i] = str;
//for showing in terminal if read correctly
cout << words[i] << " ";
}
inputFile.close();
cout << endl;
//str = "works";
The values of variable str is works.
After that, you set every elements in words by str. So every elements in the words now are the same value works.
for (int i = MAXSIZE; (outputFile << str) && (i >= 0); --i)
{
words[i] = str;//=="works"
//for showing in terminal if written correctly
cout << words[i] << " ";
}
outputFile.close();
cout << endl;