Program for a Vector of Strings - c++

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++;
}

Related

How to read more than one line of input?

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?

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 convert a string into the sum of ASCII values?

I am a beginner and taking a CSC course, I have to write a program that converts a user input string into the sum of the ASCII value of each character, here is what I have so far, and Im still pretty far from being done. But any help would be greatly appreciated. Thanks
#include <iostream>
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
using std::string;
using std::cout;
using std::endl;
int main()
{
{
int x;
std::cout << "enter string" << std::endl;
std::cin >> x;
}
string text = "STRING";
for (int i = 0; i < text.size(); i++)
cout << (int)text[i] << endl;
return 0;
}
You can use a range-based for loop to traverse the string and then add up each char within:
#include <iostream>
#include <string>
int main()
{
int sum = 0; // this is where all the values are being added to
std::string s;
std::cout << "enter string and press enter." << std::endl;
std::cin >> s; // string that the user enters will be stored in s
for (char c : s)
sum += c;
std::cout << "total ASCII values: " << sum << std::endl;
return 0;
}

Looping and strcpy

#include <iostream>
#include <string>
using namespace std;
int main()
{
int n;
cout << "Enter n: ";
cin >> n;
cout << "Enter " << n << "names";
for(int i=0; i<n; i++)
{
system("pause>0");
return 0;
}
This is my unfinished code. I'm required to enter a number then it will ask me to enter n names. and after entering the names the program should sort the names alphabetically. How will I do that in Looping? I'm very confused in the looping part. Yeah, I know what I will code when I'm finished in looping. I'm just confused and having problems in this part. Thanks in Advance!
Here's an STL version of what you're trying to do:
#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <algorithm>
int main() {
std::vector<std::string> names;
int num = 0;
std::cout << "Please enter a number: ";
std::cin >> num;
std::cout << "\n";
std::string name;
for (int i = 0; i < num; ++i) {
std::cout << "Please enter name(" << (i+1) << "): ";
std::cin >> name;
names.push_back(name);
}
//sort the vector:
std::sort(names.begin(), names.end());
std::cout << "The sorted names are: \n";
for (int i=0; i<num; ++i) {
std::cout << names[i] << "\n";
}
return 0;
}
However, this version is a case-sensitive sort, so whether or not that performs to your requirements could be problematic. So, a possible next step to get closer to case-insensitive sorting is to use this bit of code before the vector is sorted:
//transform the vector of strings into lowercase for case-insensitive comparison
for (std::vector<std::string>::iterator it=names.begin(); it != names.end(); ++it) {
name = *it;
std::transform(name.begin(), name.end(), name.begin(), ::tolower);
*it = name;
}
The only caveat with this method is that all your string will be converted to lowercase, though.
REFERENCES:
https://stackoverflow.com/a/688068/866930
How to convert std::string to lower case?

C++ program doesn't print out strings but does output double value

So here is the program I'm working on. So far it just prints out the double value in my CPP file. Note the two characters arrays I have set up. Why is this?
Molecule.h
const int MAX_STRUCT = 10;
const int MAX_NAME = 20;
class Molecule {
char molecule_structure[];
char molecule_name[];
double molecule_mass;
public:
Molecule();
bool read();
void display() const;
};
Molecule.cpp
#include <iostream>
#include <cstring>
using namespace std;
#include "Molecule.h"
Molecule::Molecule() {
molecule_structure[0] = '\0';
molecule_name[0] = '\0';
molecule_mass = 0;
}
bool Molecule::read(){
bool complete = false;
cout << "Enter structure : ";
cin.getline (molecule_structure, 10);
if (strcmp (molecule_structure, "0") != 0){
cout << "Enter full name : ";
cin.getline (molecule_name, 20);
cout << "Enter weight : ";
cin >> molecule_mass;
cin.ignore();
complete = true;
}
else {
molecule_structure[0] = '\0';
molecule_name[0] = '\0';
molecule_mass = 0;
}
return complete;
}
void Molecule::display() const
{
cout << molecule_structure << " " << molecule_name << " " << molecule_mass << endl;
}
w4x.h
const int MAX_MOLECULES = 10;
w4x.cpp
#include <iostream>
using namespace std;
#include "w4x.h"
#include "Molecule.h"
int main() {
int n = MAX_MOLECULES;
Molecule molecule[MAX_MOLECULES];
cout << "Molecular Information\n";
cout << "=====================" << endl;
for (int i = 0; i < MAX_MOLECULES; i++) {
if (!molecule[i].read()) {
n = i;
i = MAX_MOLECULES;
}
cout << endl;
}
cout << "Structure Name Mass\n";
cout << "==================================================" << endl;
for (int i = 0; i < n; i++)
molecule[i].display();
}
The errors I believe are coming from my Molecule.cpp file which is what I've been changing around.
This is the output I'm currently receiving.
Molecular Information
=====================
Enter structure : Super
Enter full name : Man
Enter weight : 57
Enter structure : 0
Structure Name Mass
==================================================
57
Changing the header Molecule.h so it uses:
const int MAX_STRUCT = 10;
const int MAX_NAME = 20;
class Molecule {
char molecule_structure[MAX_STRUCT];
char molecule_name[MAX_NAME];
double molecule_mass;
public:
Molecule();
bool read();
void display() const;
};
Makes the code work sanely.
A more thorough reworking of the code to use std::string gives:
Molecule.h
#ifndef MOLECULE_H_INCLUDED
#define MOLECULE_H_INCLUDED
#include <string>
class Molecule
{
std::string molecule_structure;
std::string molecule_name;
double molecule_mass;
public:
Molecule();
bool read();
void display() const;
};
#endif // MOLECULE_H_INCLUDED
Molecule.cpp
#include <iostream>
#include <iomanip>
#include <limits>
#include <cstring>
using namespace std;
#include "Molecule.h"
Molecule::Molecule() : molecule_structure(""), molecule_name(""), molecule_mass(0) { }
bool Molecule::read()
{
Molecule m;
cout << "Enter structure : ";
if (!getline(cin, m.molecule_structure) || m.molecule_structure == "")
return false;
cout << "Enter full name : ";
if (!getline(cin, m.molecule_name))
return false;
cout << "Enter weight : ";
if (!(cin >> m.molecule_mass))
return false;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
swap(*this, m);
return true;
}
void Molecule::display() const
{
cout << left << setw(15) << molecule_structure << " ";
cout << left << setw(20) << molecule_name << " ";
cout << setprecision(5) << molecule_mass << endl;
}
The read() function does not modify the variable it is given unless the reading is successful. There are probably better ways to handle the input, but that shown is reasonably sensible. You terminate the input with an empty line in response to the 'Enter structure:' prompt. The printf() format notations have the merit of brevity compared with what's necessary with C++ I/O streams.
w4x.cpp
No longer including w4x.h.
#include <iostream>
using namespace std;
#include "Molecule.h"
const int MAX_MOLECULES = 10;
int main()
{
int n = MAX_MOLECULES;
Molecule molecule[MAX_MOLECULES];
cout << "Molecular Information\n";
cout << "=====================" << endl;
for (int i = 0; i < MAX_MOLECULES; i++) {
if (!molecule[i].read()) {
n = i;
break;
}
cout << endl;
}
if (n > 0)
{
cout << "Structure Name Mass\n";
cout << "===================================================" << endl;
for (int i = 0; i < n; i++)
molecule[i].display();
}
}