c++ program of sorting names - visual-c++

Instruction for program:
Read the list of names from “names.txt” in the format “First Last”.
Sort the names based upon typical alphabetic order of peoples names based upon last name then first name.
Write the sorted list to a file called “sortednames.txt” in the format “Last, First”.
Here's my code: file data was stored in fullname array but now I am stuck on how to flip the first and last name in the array??
int main()
{
const int MAXNAMES = 100;
int value = 0;
string fullname[MAXNAMES];
ifstream inFile;
inFile.open("names.txt"); //open the file to excess the rainfall data
if (inFile.fail()) // testing the file
{
cout << "Error opening file. Please check that the file currently `enter code here`exist" << endl;
exit(1);
}
cout << "File successfully open" << endl;
while(!inFile.eof())
{
while(value < 100)
{
getline(inFile,fullname[value]);
value++;
}
}
return 0;
}

To flip the name around you could do the following:
string myString;
int spacePosition;
value = 0;
while(value < 100) {
myString = fullname[value];
spacePosition = myString.find(" ");
fullname[value] = myString.substr(spacePostion) + " " + myString.substr(0, spacePostion -1);
}

Related

std::string::find returns npos when the char is present in the string

In a small utility I'm writing, I want to read a file record and:
look for the presence of an XOR checksum in the form *XX, where XX are hex digits
replace it if it's incorrect
add one if it's not present
So far, I'm only to the point of reading the file and looking for the checksum. The problem I'm up against is that std::string::find is not finding the * I know to be present; it returns npos every time.
The find() is on line 37. The first line read into strInput is:
$GPGGA,14240.99,2732.581,S,15301.947,E,1,06,3,65,M,37,M,-1.0,0006*6E\n
Here's the code:
#include <iostream>
#include <string>
int main()
{
std::cout << "Enter input file name:\n";
std::string strFileName = "";
std::getline(std::cin, strFileName);
std::cout << "Filename entered: " << strFileName << '\n';
FILE* fp;
int nErrCode = EXIT_FAILURE;
fopen_s(&fp, strFileName.c_str(), "r+");
if (!fp)
{
std::string strErr = "Failed to open " + strFileName;
perror(strErr.c_str());
return nErrCode;
}
rewind(fp);
std::string strInput;
strInput.reserve(100);
std::string::size_type n;
do
{
fgets(&strInput[0], 99, fp);
std::cout << strInput.c_str();
//n = 0;
n = strInput.find('*');
if (n != std::string::npos)
std::cout << "Found checksum at position " << n;
else
std::cout << "Did not find checksum";
} while (!feof(fp));
}
Thanks in advance.
I've debugged this and all is well up to the find(). At that point, I can see that the return value is npos, even though I can see the value of strInput and verify that it contains an asterisk.

AppCenter: Find and replace string in a file during build

Is it possible to edit a .mm file before it gets compiled in AppCenter?
In an attempt to fix a build error, I want to find and replace a string in ../node_modules/react-native/React/CxxBridge/RCTCxxBridge.mm.
I tried using sed -i 's/oldString/newString/g' ../node_modules/react-native/React/CxxBridge/RCTCxxBridge.mm inside appcenter-pre-build.sh but it does not work.
Any help will be appreciated,
Thanks.
Not sure if this is your case, but I needed to update a version number on a complex project. To replace the counter of the current version with a new one, I considered updating the file with each build. After some versions of bash scripts, I realized that it's easier for me to write a console application in C with a couple of parameters to solve this problem. Works almost perfect for me. If you need I can share the simple code of this program.
Here is the C code that looks for a string in the file passed as a parameter and replaces the version number in it.
int main(int argc, char* argv[])
{
cout << "Version changer start\n";
if (argc < 2) {
cout << "There is no path argument. Version was no changed.";
return 1;
}
string sourcePath = argv[1];
string targetPath = sourcePath + ".tmp";
bool firstLine = true;
cout << sourcePath << endl;
ifstream sourceFile(sourcePath); // open file for input
ofstream targetFile(targetPath); // open file for output
string line;
while (getline(sourceFile, line)) // for each line read from the file
{
// looking for the desired line
if (line.find("public static String VER") != std::string::npos) { // replace "public static String VER" to your string definition code
line.replace(0, 32, "");
line.replace(line.length() - 2, 2, "");
int number = atoi(line.c_str());
number++; // In my case, I get an integer and add one to it
string v = to_string(number);
line = " public static String VER = \"" + v + "\";";
cout << v;
}
if (firstLine) {
targetFile << line;
firstLine = false;
}
else
targetFile << endl << line;
}
sourceFile.close();
targetFile.close();
remove(sourcePath.c_str());
if (rename(targetPath.c_str(), sourcePath.c_str()) != 0)
perror("Error renaming file");
else
cout << endl << "----------- done -----------\n";
}

No suitable constructor exists to convert from "char" to "std::string"

I'm new to coding in C and C++, and I have a program with
an issue. When I (try) to run it, it gives me this error:
"No suitable constructor exists to convert from "char" to "std::string".
I'm not sure what it means. My code is an example of a simple
substitution cipher covered in the book "Cracking Codes with Python" by Al Sweigart.
I just want to replicate it in C++. Here's my code:
#include <iostream> // for communicating with user
#include <string>
using namespace std;
string symbols = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // all symbols
string encrypt(string msg, string key, string mode) {
string ca = symbols;
string cb = key;
string translated;
if (mode == "decrypt") {
ca, cb = cb, ca;
}
int index = 0;
for (index = 0; index < msg.length(); index++) {
cout << "index is " << index << endl;
int sindex = ca.find(msg[index]); // it works here
cout << "sindex is " << sindex << endl;
string cl = cb[sindex]; // the problem
translated += cl;
}
return translated;
}
int main() {
string msg = "";
string key = "";
string mode = "";
string ciphertext = ""; // our variables
cout << "Enter message: (no spaces please)\n";
cin >> msg;
cout << "Enter key (or \"none\" for using default):\n";
cin >> key;
if (key == "none") {
key = "QWERTYUIOPASDFGHJKLZXCVBNM";
}
cout << "Enter mode: (\"encrypt\" or \"decrypt\")\n";
cin >> mode;
ciphertext = encrypt(msg, key, mode);
cout << "The ciphertext is\n" << ciphertext;
}
For some reason it works with msg on line 17 but not with cb on line 19, even though
they're both std::string. The actual error is on line 19 with string cl = cb[sindex];.
Not even sure what's wrong. It works on line 17 int sindex = ca.find(/*The thing here*/msg[index]);.
(Maybe my Visual Studio 2019 has gone nuts.) If I replace cb with msg it still gives me the
same error. Maybe line 17 is a lucky line? Who knows? But please help, I'm so
confused!

Why VS 2015 is giving me the exception at the end of the code below?

I am somewhat new to c++, our class only went over debugging briefly. This is probably my 10th do over, I have been over it a week, have done plenty of research over the web and I just don't understand debugging enough to figure out how to fix my code. The program is supposed to real a file like this:
TTFTFTTTFTFTFFTTFTTF
ABC54102 T FTFTFTTTFTTFTTF TF
DEF56278 TTFTFTTTFTFTFFTTFTTF
ABC42366 TTFTFTTTFTFTFFTTF
ABC42586 TTTTFTTT TFTFFFTF
When it reads the file it's supposed to output the student ids, what they answered on each question and the grade for each student. My problem is, I don't know much about debugging and VS keeps throwing an exception at the end of the code I provided. I am just learning how to use dynamic arrays so I know it has something to do with my use of them because I had the program working fine in my other c++ class but I had to change it around to use dynamic arrays for this project.
What's wrong with my program? I have researched the web and reread the chapters in the book over and over and I cannot figure it out.
#include <iostream>
#include <string>
#include <fstream>
#include <stdlib.h>
#include <cstddef>
using namespace std;
// function prototypes
void readFile(ifstream& inFile);
char assignGrade(int score, int numQues);
int main()
{
int numQues = 20;
int numStud = 0;
string *studentIDs;
studentIDs = new string[numStud];
char *correctAnswers;
correctAnswers = new char[numStud];
char *studentAnswers;
studentAnswers = new char[numQues];
ifstream inFile;
cout << "\nRedo Programming Exercise Six of Chapter Eight\nUsing Dynamic Arrays..." << endl;
cout << "\nPlease Enter the Number of Students: ";
cin >> numStud;
cout << endl;
readFile(inFile);
inFile.getline(correctAnswers, '/n'); // read the correct answers first
for (int i = 0; i < numStud; i++) // loop students
{
inFile >> studentIDs[i]; // get the student ID
inFile.get(); // discard the space between the student ID and the answer
for (int j = 0; j < numQues; j++) // loop questions
{
studentAnswers[j] = inFile.get(); // get the student's answers
}// end for
cout << "Student ID: " << studentIDs[i] << endl; // output student id
int score = 0; // declare and initialize score to zero
cout << "Answers: "; // display "Answers: "
for (int j = 0; j < numQues; j++) // loop each question
{
cout << studentAnswers[j]; // output student's answers
if (studentAnswers[j] == correctAnswers[j]) // if student answer equals correct answer
score += 2; // correct answer
else if (studentAnswers[j] != correctAnswers[j] && studentAnswers[j] != ' ')
score -= 1; // incorrect answer but not a blank
else if (studentAnswers[j] == ' ')
score = 0;
delete[] studentAnswers;
}// end for
if (score < 0)
score = 0; // don't allow for negative scores
cout << endl; // new line, housekeeping
char grade = assignGrade(score, numQues); // call assignGrade function
cout << "Grade: " << grade << "\n" << endl; // display grade
}// end for
delete[] studentIDs;
system("pause");
return(0);
}
void readFile(ifstream& inFile)
{
inFile.open("Ch12_Ex2Data.txt"); // use inFile to open Ch8_Ex6Data.txt
if (!inFile) // if the file can't be opened or it is corrupt
{
cout << "There was an error opening the input file...\nPlease check file and try again!\n" << endl; // display error message
system("pause");
exit(1); // exit the program
}
} // end readFile function
char assignGrade(int score, int numQues)
{
double percentScore = static_cast<double>(score) / (numQues * 2); // calculate the score percentage
cout << "Score: " << percentScore * 100 << "%" << endl; // display the score
if (percentScore >= 0.9) // if score is greater than or equal to 90%, return A
return 'A';
else if (percentScore >= 0.8) // if score is greater than or equal to 80%, return B
return 'B';
else if (percentScore >= 0.7) // if score is greater than or equal to 70%, return C
return 'C';
else if (percentScore >= 0.6) // if score is greater than or equal to 60%, return D
return 'D';
else // any score lower thn 60%, return F
return 'F';
} // end assignGrade function
It keeps breaking here in the debugger:
static void __CLRCALL_OR_CDECL assign(_Elem& _Left, const _Elem& _Right)
_NOEXCEPT
{ // assign an element
_Left = _Right;
}
// Redo Programming Exercise Six of Chapter Eight
// Using Dynamic Arrays -- C++ Advanced
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
// function prototype
void readFile(ifstream& inFile, string fileName);
int main()
{
// variables, pointers and dynamic arrays
int numStud = 200; // stores the number of students, max students was 200
int numQues = 20; // stores the number of questions on test
string *studentIDs; // pointer variable for studentIDs dynamic array
char *correctAnswers; // pointer variable for correctAnswers dynamic array
correctAnswers = new char[numQues]; // correctAnswers dynamic char array
char *studentAnswers; // pointer variable for studentAnswers dynamic array
studentAnswers = new char[numQues]; // studentAnswers dynamic char array
char *fileName; // pointer variable for fileName dynamic char array
fileName = new char[25]; // fileName dynamic char array
ifstream inFile; // input stream variable inFile
// display message to explain the program
cout << "\nJames Flowers - Chapter 12 - Programming Exercise 2" << endl;
cout << "\nRedo Programming Exercise Six of Chapter Eight\nUsing Dynamic Arrays..." << endl;
// request file name for fileName dynamic char array
cout << "\nPlease Enter the File Name (Ch12_Ex2Data.txt): ";
cin >> fileName;
cout << endl;
// call readFile function to read the file
readFile(inFile, fileName);
// request number of students for studentIDs dynamic char array and some calculations
cout << "\nHow many students took this test? (4): ";
cin >> numStud;
cout << endl;
studentIDs = new string[numStud]; // create studentIDs dynamic char array
inFile.getline(correctAnswers, '/n'); // read the correct answers first
for (int i = 0; i < numStud; i++) // loop students
{
inFile >> studentIDs[i]; // get the student ID
inFile.get(); // discard the blank space
inFile.getline(studentAnswers, '/n'); // get the student's test answers
cout << "Student ID: " << studentIDs[i] << endl; // output student id
int score = 0; // declare and initialize score to zero
cout << "Answers: "; // display "Answers: "
for (int j = 0; j < numQues; j++) // loop each question
{
cout << studentAnswers[j]; // output student's answers
if (studentAnswers[j] == correctAnswers[j]) // if student answer is correct
score += 2; // add 2 to score
else if (studentAnswers[j] != correctAnswers[j] && studentAnswers[j] != ' ') // incorrect answer but not blank
score -= 1; // subtract 1 from score
else if (studentAnswers[j] == ' ') // if question left blank
score -= 0; // nothing subtracted from score
studentAnswers[j] = ' '; // clear each indice for next student
}// end for
cout << endl; // new line, housekeeping
char grade = 0; // char variable grade initialized to 0
double percentScore = static_cast<double>(score) / (numQues * 2); // calculate the score percentage
cout << "Score: " << percentScore * 100 << "%" << endl; // display the score
if (percentScore >= 0.9) // if score is greater than or equal to 90%, return A
grade = 'A'; // grade = A
else if (percentScore >= 0.8) // if score is greater than or equal to 80%, return B
grade = 'B'; // grade = B
else if (percentScore >= 0.7) // if score is greater than or equal to 70%,
grade = 'C'; // grade = C
else if (percentScore >= 0.6) // if score is greater than or equal to 60%,
grade = 'D'; // grade = D
else // any score lower than 60%,
grade = 'F'; // grade = F
cout << "Grade: " << grade << "\n" << endl; // display grade
}// end for
system("pause"); // pause for readability
return(0);
}// end main
// readFile function reads the file, if not displays error message
void readFile(ifstream& inFile, string fileName)
{
inFile.open(fileName); // use inFile to open input file
if (!inFile.is_open()) // if the file can't be opened or it is corrupt
{
cout << "There was an error opening the input file...\nPlease check file name and try again!\n" << endl; // display error message
system("pause"); // pause for readability
exit(1);
}// end if
} // end readFile function

Removing from and Shuffling a C++ vector

I am using a vector to represent a deck of cards in c++. I am having trouble shuffling the deck and removing the first element.
Shuffling does not work, the vector keeps the same order. I call reseed once in my program, in the constructor of Deck. int random is different every time. I have tried time(NULL) and time(0). Shuffling:
void Deck::reseed() {
srand(time(NULL));
}
void Deck::shuffle() {
int random = rand();
for(int i = 0; i < random; i++) {
std::random_shuffle(deckVec.begin(), deckVec.end());
}
}
Removing does not work, the last element is removed instead of the first (for example, element 16 is erased and not element 0). Removing:
Card Deck::dealCard() {
//other code...
Card& tempCard = deckVec.front();
std::vector<Card>::iterator temp = deckVec.begin(); //This if for debugging, and
//this pointer is correct
deckVec.erase(deckVec.begin());
return tempCard; //the correct card is returned
}
Any help would be appreciated.
-----------Update----------------
code for printing before and after shuffle:
cout << deck.toString(); //output: Suit: Clubs, Rank: 2
// Suit: Clubs, Rank: 3 ...
//shuffle if there are three arguments
if(argc == 3)
deck.shuffle();
cout << deck.toString();//output: Suit: Clubs, Rank: 2
// Suit: Clubs, Rank: 3 ... (identical to above)
It's difficult to show dealCard. Basically, I call it here:
void operator<<(Hand& hand, Deck& deck) {
hand.addCard(deck.dealCard());
}
Then I print out the contents. The output is: C2 C2 C2 C2 ... for the 2 of Clubs. They are all the first card in the deck.
for(int i = 0; i < 5; i++) {
for(unsigned int j = 0; j < hands.size(); j++) {
try {
hands.at(j) << deck;
} catch(int& i) {
cout << "no cards left" << endl;
}
}
}
//print out the contents
cout << deck.toString() << endl;
for(unsigned int i = 0; i < hands.size(); i++) {
cout << "Hand " << i << ": ";
cout << hands.at(i).toString() << endl;
}

Resources