How to read more than one line of input? - c++

So I have built a small basic data encrypter (for learning purposes only). It is working perfectly fine but it reads only a single line of input. Is it my Editor problem or my code have some issues.
ps: I use CodeBlocks
#include <iostream>
#include <ctype.h>
using namespace std;
int main()
{
std::string str;
char enc;
int word;
cout << "\t\t\t\t\t\t\t\tENCRYPTOR" <<endl;
cout << "\t\t\t\t\t\t\t\t---------" <<endl;
cout << "Enter a Word: ";
getline(cin, str);
int n = 0;
cout << "\n\n\t\t\t\t\t\t\t\tENCRYPTED D#T#" <<endl;
cout << "\t\t\t\t\t\t\t\t--------------\n\n" << endl;
for(int i = 0; i < str.length(); i++){
int randomAdd[5] = {5,6,2,3,2};
int size = sizeof(randomAdd)/sizeof(randomAdd[0]);
// for(int j = 0; j < 5; j++){
word = str.at(i);
if(i%5 == 0){
n = 0;
}
enc = int(word) + randomAdd[n];
std::cout << char(enc);
n++;
}
return 0;
}
This works
Hello World
But I cannot enter this
Hello World
Have a nice day
because then the program exits command prompt without any error or message.
How can I read more than one line?

You can do as
#include <iostream>
using namespace std;
int main() {
string str;
while (getline(cin, str)) {
cout << str << endl;
}
return 0;
}

This code sample allows you to input multiple lines interactively from the command line/shell
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string str;
char enc;
int word;
vector<string> myInput;
cout << "\t\t\t\t\t\t\t\tENCRYPTOR" <<endl;
cout << "\t\t\t\t\t\t\t\t---------" <<endl;
while (str != "Enigma")
{
cout << "Enter a line (Write Enigma to exit input): ";
getline(cin, str);
myInput.push_back(str);
}
int n = 0;
cout << "\n\n\t\t\t\t\t\t\t\tENCRYPTED D#T#" <<endl;
cout << "\t\t\t\t\t\t\t\t--------------\n\n" << endl;
for(auto & myInputLine : myInput)
{
str = myInputLine;
for (size_t i = 0; i < str.length(); i++) {
int randomAdd[5] = { 5,6,2,3,2 };
int size = sizeof(randomAdd) / sizeof(randomAdd[0]);
word = str.at(i);
if (i % 5 == 0) {
n = 0;
}
enc = int(word) + randomAdd[n];
std::cout << char(enc);
n++;
}
}
return 0;
}
The input is finished if Enigma is written.
All input is stored in the vector container of the STL, see vector.
Afterwards, all the lines are encrypted by your algorithm.
Hope it helps?

Related

How to fix vector not printing values from file

I am trying to get some values line by line from a text file:
17.09 284.60 486.01 34.12 12.04 1.20 2.33 36.85 73.44
31.25 196.09 323.26 69.76 47.33 79.82 11.42 27.97 66.61
28.76 41.45 992.29 1.29 42.33 10.83 19.16 5.86 1.88
Taking these values and putting it into a vector. Each row has values to be used in a calculation.
My code:
#include <iostream>
#include <fstream>
#include <string>
#include <iterator>
#include <vector>
using namespace std;
int main() {
ifstream xfile;
string input;
double num=0;
int count = 0;
vector <double> myvector;
cout << "Input the file: ";
cin >> input;
xfile.open(input);
if (xfile.is_open()) {
cout << "File accessed!" << endl;
while (getline(xfile, input)) {
count++;
myvector.push_back(num);
}
}
else {
cout << "File opening failed!"<<endl;
}
cout << "Numbers of lines in the file : " << count << endl;
for (int i = 0; i < myvector.size(); i++) {
cout << myvector[i] << "\t";
}
cin.fail();
return 0;
}
My output is somewhat correct, only that it is printing out just zeroes:
https://ibb.co/xqwT1hR
EDIT: the input is for the name of file. "ahu_long.txt"
You never used your num variable.
double num=0;
....
....
size_t pos = 0;
std::string token;
while (getline(xfile, input)) {
count++;
// you need convert your "input" to a double and save it to "num"
while ((pos = input.find(" ")) != std::string::npos) {
token = input.substr(0, pos);
// std::cout << token << std::endl;
num = atof(token.c_str());
myvector.push_back(num);
input.erase(0, pos + delimiter.length());
}
}
Change your variable with what you read from the file.

How to read a 2d array from a file without knowing its length in C++?

Like the title says I'm trying to read an unknown number of integers from a file and place them in a 2d array.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream f;int i,j,n,a[20][20];char ch;
i=0;j=0;n=0;
f.open("array.txt", ios::in);
while(!f.eof())
{
i++;
n++;
do
{
f>>a[i][j];
j++;
f>>ch;
}
while(ch!='\n');
}
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
cout<<a[i][j]<<endl;
cout<<endl;
}
return 0;
}
and my "array.txt" file :
1 1 1
2 2 2
3 3 3
After compiling the program, it prints this
As your input file is line oriented, you should use getline (C++ equivalent or C fgets) to read a line, then an istringstream to parse the line into integers. And as you do not know a priori the size, you should use vectors, and consistently control that all lines have same size, and that the number of lines is the same as the number of columns.
Last but not least, you should test eof immediately after a read and not on beginning of loop.
Code becomes:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main()
{
fstream f;
int i=0, j=0, n=0;
string line;
vector<vector<int>> a;
f.open("array.txt", ios::in);
for(;;)
{
std::getline(f, line);
if (! f) break; // test eof after read
a.push_back(vector<int>());
std::istringstream fline(line);
j = 0;
for(;;) {
int val;
fline >> val;
if (!fline) break;
a[i].push_back(val);
j++;
}
i++;
if (n == 0) n = j;
else if (n != j) {
cerr << "Error line " << i << " - " << j << " values instead of " << n << endl;
}
}
if (i != n) {
cerr << "Error " << i << " lines instead of " << n << endl;
}
for(vector<vector<int>>::const_iterator it = a.begin(); it != a.end(); it++) {
for (vector<int>::const_iterator jt = it->begin(); jt != it->end(); jt++) {
cout << " " << *jt;
}
cout << endl;
}
return 0;
}
You may want to look into using a vector so you can have a dynamic array.
Try:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main() {
fstream f;
int i, j, n, a[20][20];
string buf;
i = 0;
j = 0;
n = 0;
f.open("array.txt", ios::in);
while (1) {
getline(f, buf);
if (f.eof()) break;
stringstream buf_stream(buf);
j = 0;
do {
buf_stream >> a[i][j];
j++;
} while (!buf_stream.eof());
i++;
n++;
}
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) cout << a[i][j] << " ";
cout << endl;
}
return 0;
}
Also, if you really want to read arbitrarily large arrays, then you should use std::vector or some such other container, not raw arrays.

Unexpected abort in C++

I have a piece of code I'm running in Cygwin in C++ I'm compiling using
g++ -o program program.cpp
And it is returning an error that reads 'Aborted (core dumped)'. It is intended to take a file name as input through a command line argument, count all the unique words and total words in the file, and prompts the user to input a word and counts how many times the word that they input occurs. It's only intended to use C++ streams for input/output.
#include <fstream>
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main(int argc, char *argv[])
{
string filename;
for( int i = 1; i < argc; i++){
filename+=argv[i];
}
ifstream file;
file.open(filename.c_str());
if (!file)
{
std::cerr << "Error: Cannot open file" << filename << std::endl;
return 1;
}
string* words;
int* wordCount;
int wordLength = 0;
string curWord = "";
bool isWord;
int total = 0;
char curChar;
string input;
while(!file.eof())
{
file.get(curChar);
if (isalnum(curChar)) {
curWord+=tolower(curChar);
}
else if (!curWord.empty() && curChar==' ')
{
isWord = false;
for (int i = 0; i < wordLength; i++) {
if (words[i]==curWord) {
wordCount[i]++;
isWord = true;
total++;
}
}
if (!isWord) {
words[wordLength]=curWord;
wordLength++;
total++;
}
curWord="";
}
}
file.close();
// end
cout << "The number of words found in the file was " << total << endl;
cout << "The number of unique words found in the file was " << wordLength << endl;
cout << "Please enter a word: " << endl;
cin >> input;
while (input!="C^") {
for (int i = 0; i < wordLength; i++) {
if (words[i]==input) {
cout << wordCount[i];
}
}
}
}
You never allocated any space for words and wordCount to point to. It should be:
#define MAXWORDS 1000
string *words = new string[MAXWORDS];
int *wordCount = new int[MAXWORDS];
and then at the end of the program you should do:
delete[] wordCount;
delete[] words;
or you can allocate a local array:
string words[MAXWORDS];
int wordCount[MAXWORDS];
But you could do it more simply by using std::map to map the string to a count. This will automatically grow as needed.

Program for a Vector of Strings

I created a program that asks the user to enter 5 names which is recorded into a vector of strings. Afterwards the program is supposed to grab the first and last letters of each name and output them. My program compiles fine however after entering the names I get no output from the program.
Can anyone help me correct this issue so that it prints the first and last characters of each name entered?
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> names;
char first_letter;
char last_letter;
string name;
int n = 0;
for (int i =0; i < 5; i++)
{
cout << " Please enter a name: ";
cin >> name;
names.push_back(name);
}
if ( !names[n].empty() )
{
first_letter = *names[n].begin();
last_letter = *names[n].rbegin();
cout << first_letter << " " << last_letter << endl;
n++;
}
return 0;
}
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> names;
char first_letter;
char last_letter;
string name;
int n = 0;
for (int i =0; i < 5; i++)
{
cout << " Please enter a name: ";
cin >> name;
names.push_back(name);
}
vector<string>::iterator itr = names.begin();
for(;itr!=names.end();itr++)
{
first_letter = *itr[n].begin();
last_letter = *itr[n].rbegin();
cout << first_letter << " " << last_letter << endl;
}
return 0;
}
You have entered it as a if statement. Change it to a while loop
while ( !names[n].empty() )
{
first_letter = *names[n].begin();
last_letter = *names[n].rbegin();
std::cout << first_letter << " " << last_letter << endl;
n++;
}

Can someone please tell me why this code doesnt print anything?

I have to write a code that compares three text files and i cant for the life of me find out why this wont print anything:
#include <iostream>
#include <cstring>
#include <string>
#include <fstream>
using namespace std;
int main (int argc, char *argv[])
{
ifstream mousefile;
mousefile.open(argv[1]);
string mouse_dna;
getline(mousefile, mouse_dna);
ifstream humanfile;
humanfile.open(argv[2]);
string human_dna;
getline(humanfile, human_dna);
ifstream unknownfile;
unknownfile.open(argv[3]);
string unknown_dna;
getline(unknownfile, unknown_dna);
int len = mouse_dna.size();
int mouseDistance = 0, humanDistance = 0;
for(int i=0; i<len; i++)
if(mouse_dna[i] != unknown_dna[i])
mouseDistance++;
return mouseDistance;
for(int i=0; i<len; i++)
if(human_dna[i] != unknown_dna[i])
humanDistance++;
return humanDistance;
double similarity_scoreH = (len - humanDistance) / len;
double similarity_scoreM = (len - mouseDistance) / len;
cout << "MouseCompare = " << similarity_scoreM << endl;
cout << "HumanCompare = " << similarity_scoreH << endl;
if (similarity_scoreH == similarity_scoreM)
cout << "identity cannot be determined" << endl;
else if (similarity_scoreH > similarity_scoreM)
cout << "human" << endl;
else if (similarity_scoreM > similarity_scoreH)
cout << "mouse" << endl;
}
It compiles properly, and doesn't give any errors, but when i rut it as:
./DNA mouseDNA.txt humanDNA.txt unknownDNA.txt
it still does nothing.
I appreciate any help. Thanks!
It doesn't print anything because it's returning before the instructions to print (return mouseDistance; or return humanDistance;). Make your function more verbose by printing progress messsages before each return statement.
As already has pointed out, you return too early. I modify your code:
I put brackets around the if block and for block.
I have a return statement at the end.
This is a start. You may have to add more checking, for example, if the file is open correctly.
#include <iostream>
#include <cstring>
#include <string>
#include <fstream>
using namespace std;
int main (int argc, char *argv[])
{
ifstream mousefile;
mousefile.open(argv[1]);
string mouse_dna;
getline(mousefile, mouse_dna);
ifstream humanfile;
humanfile.open(argv[2]);
string human_dna;
getline(humanfile, human_dna);
ifstream unknownfile;
unknownfile.open(argv[3]);
string unknown_dna;
getline(unknownfile, unknown_dna);
int len = mouse_dna.size();
int mouseDistance = 0, humanDistance = 0;
for(int i=0; i<len; i++)
{
if(mouse_dna[i] != unknown_dna[i])
{
mouseDistance++;
}
}
for(int i=0; i<len; i++)
{
if(human_dna[i] != unknown_dna[i])
{
humanDistance++;
}
}
double similarity_scoreH = (len - humanDistance) / len;
double similarity_scoreM = (len - mouseDistance) / len;
cout << "MouseCompare = " << similarity_scoreM << endl;
cout << "HumanCompare = " << similarity_scoreH << endl;
if (similarity_scoreH == similarity_scoreM)
cout << "identity cannot be determined" << endl;
else if (similarity_scoreH > similarity_scoreM)
cout << "human" << endl;
else if (similarity_scoreM > similarity_scoreH)
cout << "mouse" << endl;
return 0;
}
You use arg[1], arg[2], and arg[3]. You may want arg[0], arg[1], and arg[2].