This is the code in the main() portion of the program:
int numFiles;
cout << "How many signal files are there?";
cin >> numFiles;
char singalFiles[numFiles][100];
string backgroundFile;
for (int i=0;i<numFiles;i++){
string singalFile;
cout << "Please input the name of singal file" << i << ".";
cin >> singalFile;
singalFile >> char singalFiles[i][100];
string backgroundFile;
cout << "Please input the name of background file" << i << ".";
cin >> singalFile;
backgroundFile >> char backgroundFiles [i][100];
}
This is the code I am writing as part of a research project. I was wondering if somebody could help me with this. I am very new to c++ and do not know how to get the strings to write into a char array.
I am having trouble reading the strings into the char array so they can be stored there. That is, I am trying to read each of the strings called backgroundFile and signalFile into the char arrays backgroundFiles and singalFiles.
The definition char singalFiles[numFiles][100]; may be an issue as standard C++ requires the size of an array be constant. Some compilers accept this as an extension, but you shouldn't rely on it.
But as easy alternative, you can use vectors and strings:
vector<string> singalFiles(numFiles);
Then you can easily read the data:
//cin >> singalFile; ==> combine with the next line
// singalFile >> char singalFiles[i][100];
cin >> singalFiles[i];
You don't even have to reserve for the size in advance. You could as well do:
vector<string> singalFiles; // the size of a vector is dynamic anyway !
...
cin >> singalFile; // as you did before
signalFiles.push_back(signalFile); // add a new element to the end of the vector.
Related
I have declared a string array of [15]. Actually to store names. I execute it fine, but when I enter the complete name (including space; First name+[space]+last name) the program misbehaves. I cannot find the fault
I have declared multiple string arrays in the program, when I input the name with space it doesn't executes fine. I am using cin>> function to input in the array. like
string name[15];
int count=0; cout << "enter your name" << endl;
cin >> name[count];
I am using cin>> function to input in the array.
That is the problem. operator>> is meant for reading formatted input, so it stops reading when it encounters whitespace between tokens. But you want unformatted input instead. To read a string with spaces in it, use std::getline() instead:
string name[15];
int count=0;
cout << "enter your name" << endl;
getline(cin, name[count]);
Online Demo
I am trying to read in an essay from a file which I then need to change each beginning letter of a sentence to an upper case letter and then send the corrected essay back to a file called correct.txt. The essay is stored in essay.txt.
So far I am just working with understanding the conversions from files to string in order for me to proceed with the rest of the question. So far, I have a string variable which which holds the essay with the words separated by a single space. I noticed that when I was trying to work with the size of my new string, it was not giving me the correct answer and I cannot figure out why. If you have any suggestions on how I can get it to notice the correct amount of characters, I would really appreciate it.
One more question while you're here, I know that moving forward, in order to change the beginning letters of the sentence to upper case, I need to first find the periods. Once I have this position, I can use pos+2 (including the preceding whitespace after the period) for the character that needs to become upper case. Is this the correct way of going about this and do you have any other tips on how to go forward with this?
Here is my code so far:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main(){
//declaring variables and creating objects
ifstream inputFile;
ofstream outputFile;
char inputFileName[20], outFileName[20];
cout << "Enter name of the file you want to open: " << endl;
cin >> inputFileName;
inputFile.open(inputFileName);
if (inputFile.fail()) {
cout << "Input file opening failed.\n";
exit(1);
}
cout << "Enter name of the file you want to send the output to: " << endl;
cin >> outFileName;
outputFile.open(outFileName);
if (outputFile.fail()) {
cout << "Output file opening failed.\n";
exit(1);
}
//while the file is open, it sends the contents to the string variable "essay"
string essay;
inputFile >> essay;
while (!inputFile.eof()) {
cout << essay << " ";
inputFile >> essay;
}
//this is to check for the correct size of the string "essay" before moving on to the rest of the code
int size = essay.size();
cout << size << endl;
return 0;
}
Your understanding of how the input stream works is incorrect.
The core of your code is this loop:
string essay;
inputFile >> essay;
while (!inputFile.eof()) {
cout << essay << " ";
inputFile >> essay;
}
What this does is that it reads the first word into essay, then, as long as the eof marker is not set on the stream it echoes back the word just read, and then reads another word, overwriting the previous one.
Here's the correct code. Note that checking for eof in a loop condition is a bad idea, because it doesn't quite do what you want, and would also get you stuck in an infinite loop if the stream instead entered an error condition.
string word;
while (inputFile >> word) { // read a word and stop if this fails for any reason
essay += word;
essay += " ";
}
Though I'm not sure why you read the file word by word instead of all at once.
Also, I feel the need to repeat what M.M. said in a comment: your use of raw character arrays on input is unsafe and unnecessary. Just use string. You need to then write inputFile.open(inputFileName.c_str()) unless your standard library is new enough to have the string overloads of these functions, but that is fine. The other way of doing it is dangerous and a very bad habit to get into.
Try include cstring on top of string as well.
String is considered char array which is a more 'unique' way of storing data. You can try the code listed below.
int size = essay.length();
I was going through a code in my school textbook, wherein there is a line who's function is to clear the input buffer (mentioned as a comment in the code).
I couldn't quite understand its purpose. It is definitely required as its removal messes up the console input process.
Please explain what its function is, and what is happening when I remove it.
I have also tried using cin.ignore(); and it works just fine too. How is the function used here, is it an exact replacement of cin.ignore()?
P.S. In school we are using the older version of C++. Hence the ".h" extension, clrscr();, etc.
#include <iostream.h>
#include <fstream.h>
#include <conio.h>
void main(){
clrscr();
ofstream fout("student.txt", ios::out);
char name[30], ch;
float marks = 0.0;
for(int i = 0; i < 5; i++){
cout << "Student " << (i+1) << ":\tName: ";
cin.get(name,30);
cout << "\t\tMarks: ";
cin >> marks;
cin.get(ch); //for clearing input buffer (This thing!)
fout << name << '\n' << marks << '\n';
}
fout.close();
ifstream fin("student.txt", ios::in);
fin.seekg(0);
cout << "\n";
for(int i = 0; i < 5; i++){
fin.get(name,30);
fin.get(ch); //Again
fin >> marks;
fin.get(ch); //Same
cout << "Student Name: " << name;
cout << "\tMarks: " << marks << "\n";
}
fin.close();
getch();
}
cin >> marks;
cin.get(ch); //for clearing input buffer (This thing!)
This is a not-so-robust way of clearing the input buffer. If you type a number followed by Enter, the first line will consume the number and put the value in marks while the second line will read the newline character and discard it.
It is not robust since it does not account for spaces a user might have entered after the number. A more robust method would be to use istream::ignore.
cin >> marks;
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
I just want to start with pointing out that you are not using "the older version of C++". You are just using some c code (like clrscr()) and c styled programming, and indeed probably not cpp11 or cpp14. Also header files for C++ are often still just .h.
Now the answer to your question:
cin.get(ch);
The '\n' character gets read into ch. '\n' is one character, a newline character.
does indeed do the same thing as
cin.ignore();
It is used to clear the input buffer, which means that the empty end of line ('\n') is being deleted from the input buffer.
Why is this done you ask? This is a good example of why you would do that. Hope this helped you!
Here is my code:
#include <iostream>
using namespace std;
int main(){
char inp[5], out[4];
cin >> inp >> out;
cout << inp << endl;
cout << out << endl;
system("pause");
return 0;
}
when I type:
12345
6789
It gives me:
6789
Why I failed to save the 5 words char array 'inp' and it showed nothing? The second input looks normal though. However, when I set out[3] or out[5], it seems to work alright? It seem that two char array of [5] then followed by [4] would cause problem...
I see that you enter (type) 1234567890 characters to input data for inp[5] - it is a problem because imp array is able to store 4 characters and null-terminator. When cin >> inp store more than 4 characters to inp array it leads to problem with data (somthing like undefined behaviour). So solution can be in allocation more memory for data, e.g.:
#include <iostream>
using namespace std;
int main(){
char inp[15], out[15]; // more memory
cin >> inp >> out;
cout << inp << endl;
cout << out << endl;
system("pause");
return 0;
}
When you read into a character array the stream keeps reading until it encounters whitespace, the stream is not aware of the size of the array that you pass in so happily writes past the end of the array so if your first string is longer than 4 characters your program will have undefined behaviour (an extra character is used after your input for the null terminator).
Fortunately c++20 has fixed this issue and the stream operators no longer accept raw char pointers and only accept arrays and will only read up to size - 1 characters.
Even with c++20 the better solution is to change your types to std::string which will accept any number of characters end even tell you how many characters it contains:
#include <iostream>
int main(){
std::string inp, out;
std::cin >> inp >> out;
std::cout << inp << "\n";
std::cout << out << "\n";
return 0;
}
Its because, in memory layout of computer out[4] is laid out first and then inp[5]. Something like this:
out[0],out[1],out[2],out[3],inp[0],inp[1],inp[2],inp[3],inp[4]
So, when you write 6789 in out[4], you are overflowing null character to inp[0]. So, inp becomes NULL.
I tried to input data with gets() function, but whenever program execution get to the the lien with the gets, it ignores it.
When I use gets() without previous data input, it runs properly. But when I use it after data input the problem happens.
Here's the code where it is used after previous data input (so in execution I can't input data to string):
int main() {
char str[255];
int a = 0;
cin >> a;
if(a == 1) {
gets(str);
cout << "\n" << str << endl;
}
}
How could I fix this?
NB: the same happens with cin.getline
After
cin >>a
when you input a and enter, there is also a \n character left by cin, therefore, when you use cin.getline() or gets(str) it will read that newline character.
try the following:
cin >>a;
cin.ignore(); //^^this is necessary
if(a==1){
gets(str);
}
You'd better use C++ way of reading input:
cin >> a;
cin.ignore();
string str;
if (a == 1)
{
getline(cin, str);
}