Printing the searched line - c++

I want to search for a name from a list of names and if its found I should return the whole info of that person else not found. I dont know why my code is not working. I can print the info of the person, eg:
Input:
3
Steve 9812761810 017
Wayne 8299915781 102
Ronnie 9161462903 120
Wayne
Output:
Wayne 8299915781 102
#include <iostream>
#include <string.h>
using namespace std;
int main() {
string name[100];
long long number[100];
int year[100], i, n, check = 0;
string inp;
cin >> n;
for (i = 0; i < n; i++) {
cin >> name[i] >> number[i] >> year[i];
}
cin >> inp;
for (i = 0; i < n; i++) {
if (inp == name[i]) {
check = 1;
}
}
if (check == 0)
cout << "Info Not found";
else
cout << "The Entered Name is found";
for (i = 0; i < n; i++)
cout << name[i] << number[i] << year[i];
return 0;
}

After reading an integer from the input stream, you should use cin.ignore(); before reading any strings from the input stream.
cin.ignore(); ignores the "new line" character.
Your modified code:
#include <iostream>
#include <string.h>
using namespace std;
int main() {
string name[100];
long long number[100];
int year[100], i, n, check = 0;
string inp;
cin >> n;
cin.ignore();
for (i = 0; i < n; i++) {
cin >> name[i] >> number[i] >> year[i];
cin.ignore();
}
cin >> inp;
for (i = 0; i < n; i++) {
if (inp == name[i]) {
check = 1;
}
}
if (check == 0)
cout << "Info Not found";
else
cout << "The Entered Name is found";
for (i = 0; i < n; i++)
cout << name[i] << number[i] << year[i];
return 0;
}
Read more here: Using getline(cin, s) after cin

At the end of the program, you are ignoring the value of check and just printing everything in your list regardless of whether the entered name was actually found or not.
Try something more like this instead:
#include <iostream>
#include <string>
using namespace std;
int main() {
string name[100];
long long number[100];
int year[100], i, n, idx = -1;
string inp;
cin >> n;
for (i = 0; i < n; i++) {
cin >> name[i] >> number[i] >> year[i];
}
cin >> inp;
for (i = 0; i < n; i++) {
if (inp == name[i]) {
idx = i;
break;
}
}
if (idx == -1)
cout << "Info Not found";
else {
cout << "The Entered Name is found: ";
cout << name[idx] << " " << number[idx] << " " << year[idx];
}
return 0;
}
You might also consider using a struct to organize your data better, eg:
#include <iostream>
#include <string>
using namespace std;
struct myData {
string name;
long long number;
int year;
};
istream& operator>>(istream &is, myData &data) {
is >> data.name >> data.number >> data.year;
return is;
}
ostream& operator<<(ostream &os, const myData &data) {
os << data.name << " " << data.number << " " << data.year;
return os;
}
int main() {
myData data[100];
int i, n, idx = -1;
string inp;
cin >> n;
for (i = 0; i < n; i++) {
cin >> data[i];
}
cin >> inp;
for (i = 0; i < n; i++) {
if (inp == data[i].name) {
idx = i;
break;
}
}
if (idx == -1)
cout << "Info Not found";
else
cout << "The Entered Name is found: " << data[idx];
return 0;
}

Related

after inputting the values how can i display the values under one bracket e.g "{6,7,8,9}

#include <iostream>
using namespace std;
int main(){
int n;
cout << "No. of values : ";
cin >> n;
int array[n];
for (int i=0; i<n; i++)
{
cin >> array[i];
}
return 0;
}
You can use std::cout like :
#include <iostream>
using namespace std;
int main(){
int n;
cout << "No. of values : ";
cin >> n;
int array[n];
for (int i=0; i<n; i++)
{
cin >> array[i];
if(i ==0)
std::cout<<"{" <<array[i];
else if(i == n-1)
std::cout<<","<<array[i]<<"}";
else
std::cout<<","<<array[i];
}
return 0;
}
#mystic's answer uses arrays, which works fine. You can also use vector. There are more advanced methods of iterating over a vector, but I have not included that here to keep it simple.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> intVector{};
int n;
int input;
cout << "No. of values : ";
cin >> n;
for (int i = 0; i < n; i++) {
cin >> input;
intVector.push_back(input);
}
// Print out the array
cout << "{";
for(int i = 0; i < intVector.size(); i++) {
cout << intVector[i];
// print out the comma, except for the last number
if(i < intVector.size() - 1) {
cout << ", ";
}
}
cout << "}" << endl;
return 0;
}
If you want to use an iterator for printing the array, you can replace the print loop with this code:
// Print out the array
cout << "{";
for(auto i=intVector.begin(); i!=intVector.end(); ++i) {
if (i != intVector.begin()) {
cout << ", ";
}
cout << *i;
}
cout << "}" << endl;

C++ My files were working before I attempted to move them into a source file, and now there are no errors and nothing being displayed

My apologies for being a little vague about the issue(s) in the topic, but I really am not sure. I am attempting to create a course_directory as a lab project for school, and up until now everything had been progressing quite well. I have written and tested each of the function in the main.cpp before attempting to move the class functions into the .hpp file. My goal is to have nothing in main except for a call to "Run" that will open a file, and in turn make a call to "displayMenu", and allow the user to interact with the information as they choose, but now everything is compiling correctly, and nothing is being displayed.
Course_directory.hpp
#include "Course_Directory.h"
using namespace std;
Course_Directory::Course_Directory(){};
Course_Directory courses[1001];
void Course_Directory::displayMenu(){
cout << "1.Print all courses" << endl;
cout << "2.Print all courses for a department" << endl;
cout << "3.Print roster for a course" << endl;
cout << "4.Print the largest class" << endl;
cout << "5.Swap two classes" << endl;
cout << "6.Print schedule for a student" << endl;
cout << "7.Exit" << endl;
char dept[50], dept2[50];
int courseNo, courseNo2, i, choice;
while (choice != 7) {
cout << "\nEnter your choice: ";
cin >> choice;
if (choice == 1)
printAllCourses(i);
else if (choice == 2) {
cout << "\nEnter department name:";
cin >> dept;
for(int j = 0; j < sizeof(dept); j++)
{
dept[j] = (toupper(dept[j]));
}
coursesInDept(dept, i);
}
else if (choice == 3) {
cout << "\nEnter course number:";
cin >> courseNo;
studentsInCourse(courseNo, i);
}
else if (choice == 4) {
largestClass(i);
}
else if (choice == 5) {
cout << "\nEnter first department name :";
cin >> dept;
for(int j = 0; j < sizeof(dept); j++)
{
dept[j] = (toupper(dept[j]));
}
cout << "\nEnter first course number: ";
cin >> courseNo;
cout << "\nEnter second department name :";
cin >> dept2;
for(int k = 0; k < sizeof(dept2); k++)
{
dept2[k] = (toupper(dept2[k]));
}
cout << "\nEnter second course number: ";
cin >> courseNo2;
swap2(dept, courseNo, dept2, courseNo2, i);
}
else if (choice == 6) {
int id;
cout << "\nEnter a student Id:";
cin >> id;
schedule(id, i);
}
}
cout << "Goodbye!\n";
}
void Course_Directory::printAllCourses(int len){
for (int i = 0; i < len; i++)
cout << "Course name: " << courses[i].courseName << ", Course
number: " << courses[i].courseNum << endl;
cout << len;
}
void Course_Directory::coursesInDept(char *dept, int len) {
for (int i = 0; i < len; i++)
if (strcmp(dept, courses[i].courseName) == 0)
cout << "Course Name: " << courses[i].courseName << ",
Course number: " << courses[i].courseNum << endl;
}
void Course_Directory::studentsInCourse(int courseNo, int len) {
for (int i = 0; i < len; i++)
if (courseNo == courses[i].courseNum) {
for (int m = 0; m < courses[i].numStudents - 1; m++)
cout << courses[i].IDs[m] << ",";
cout << courses[i].IDs[courses[i].numStudents - 1] <<
endl;
}
}
void Course_Directory::largestClass(int len) {
int max = -999;
for (int i = 0; i < len; i++) {
if (courses[i].numStudents > max)
max = courses[i].numStudents;
}
for (int i = 0; i < len; i++) {
if (courses[i].numStudents == max){
cout << "\nThe largest class is in department: " <<
courses[i].courseName
<< ", and the course number is: " << courses[i].courseNum
<< "\n";
cout << "The class currently has " << max << " students
enrolled.\n";
}
}
}
void Course_Directory::swap2(char *firstDep, int firstNo, char
*secondDep, int secondNo, int len) {
Course_Directory temp;
int firstIndex, secondIndex;
for (int i = 0; i < len; i++) {
if (strcmp(firstDep, courses[i].courseName) == 0 &&
courses[i].courseNum == firstNo)
firstIndex = i;
if (strcmp(secondDep, courses[i].courseName) == 0 &&
courses[i].courseNum == secondNo)
secondIndex = i;
}
temp = courses[firstIndex];
courses[firstIndex] = courses[secondIndex];
courses[secondIndex] = temp;
}
void Course_Directory::schedule(int id, int len) {
cout << "Courses student " << id << " is enrolled in: " << endl;
for (int i = 0; i < len; i++) {
for (int j = 0; j < courses[i].numStudents; j++)
if (courses[i].IDs[j] == id)
cout << courses[i].courseNum << " \n";
}
}
Course_Directory.h
#ifndef COURSE_DIRECTORY_H
#define COURSE_DIRECTORY_H
#include <iostream>
using namespace std;
class Course_Directory{
private:
int* deptSize;
string filename;
public:
char courseName[1001];
int courseNum;
int numStudents;
int IDs[1001];
int* choice;
void displayMenu();
Course_Directory();
//Course_Directory(const Course_Directory& original);
//~Course_Directory();
//void run(string);
void coursesInDept(char*, int);
void studentsInCourse(int, int);
void largestClass(int);
void swap2(char*, int, char*, int, int);
void schedule(int, int);
void printAllCourses(int);
};
#include "Course_Directory.hpp"
#endif //COURSE_DIRECTORY_H
main.cpp
#include "Course_Directory.h"
using namespace std;
class Course_Directory;
int main() {
ifstream file;
file.open("input.txt");
char *token;
int i = 0, j;
Course_Directory courses[100];
if (!file.fail()) {
std::string line;
while (getline(file, line)) {
j = 0;
char *str = const_cast<char *>(line.c_str());
token = strtok(str, " ");
while (token != NULL)
{
if (j == 0)
strcpy(courses[i].courseName, token);
else if (j == 1)
courses[i].courseNum = atoi(token);
else if (j == 2)
courses[i].numStudents = atoi(token);
else
courses[i].IDs[j - 3] = atoi(token);
j++;
token = strtok(NULL, " ");
cout << courses[i].courseName << endl;
}
i++;
}
file.close();
}
else{
cout << "File not found." << endl;
}
//menu
Course_Directory displayMenu();
return 0;
}
If I leave Course_Directory off of displayMenu(); then I get "displayMenu" was not declared in this scope. I'm not sure what the problem is or why the menu will not display. Any help would be greatly appreciated!

Insertion Sort Initiation

I am brand new to stack overflow here so thank you all for your patience in helping me with my issue. I am writing a program in C++ that implements the insertion sort by sorting numbers from a .txt file. It accepts a file, shows the contents and then asks the user if they want to sort the numbers. When I key "y" it is supposed to initiate the insertion sort algorithm in my code. However right now all it does is finish compiling. Any advice is greatly appreciated.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//Read file input and display contents
ifstream& readfile(ifstream& file)
{
string line;
if (getline(file, line))
{
cout << line;
}
return file;
}
int main()
{
string fileName, line, r;
int n, i, j, k, temp;
int a[n];
ifstream fs;
cout << "enter file: ";
cin >> fileName;
ifstream file(fileName);
if (file.is_open())
{
while (readfile(file))
{
}
}
cout << endl << endl << "Sort File? y or n? ";
cin >> r;
if (r == "y")
{
for (i = 0; i < n; i++)
{
cin >> a[i];
}
for (i = 1; i < n; i++)
{
for (j = i; j >= 1; j--)
{
if (a[j] < a[j - 1])
{
temp = a[j];
a[j] = a[j - 1];
a[j - 1] = temp;
}
else
{
break;
}
}
}
for (k = 0; k < n; k++)
{
cout << a[k] << endl;
}
}
else
{
cout << endl << "error" << endl;
}
cin.get();
return 0;
}
n is not initialized.
for (i=0;i<n;i++)
{
cin >> a[i];
}
here nothing happen because (if your are lucky...) n=0.
Initialize n to 5 if you want only 5 entries.
or
use STL containers like std::vector for example, you are using C like language here...
Change your end condition in your loop when users initialize insertion
For example if user insert "stop" word:
std::vector<int> vIntegers;
std::string input;
int n = 0;
while ( input != "stop")
{
std::cin >> input;
// test if integer here
{
vIntegers.push_back(n);
}
}
here the post to test if a string is an integer
How do I check if a C++ string is an int?

lower string characters and add a _ in front of converted capital letter

I have one more question, I want to add a _ in front of every Capital letter which will be converted to lowercase, plus the first letter cannot be capital!! I cant figure out how to do it... :{ example:
input: loLollL, output: lo_loll_l
and I want it to go backwards too: input: lo_loll_l output: loLollL
code is here:
#include <iostream>
#include <algorithm>
using namespace std;
int main ()
{
const int max = 100;
string slovo;
int pocet_r;
cout << "Zadaj pocet uloh:" << endl;
cin >> pocet_r;
if(pocet_r >= 1 && pocet_r <=100)
{
// funkcia na zabezpecenie minimalneho poctu chars
for (int i = 0; i <pocet_r; i++)
{
cout << "Uloha " << i+1 << ":" << endl;
cin >> slovo;
if(slovo.size() > max)
{
cout << "slovo musi mat minimalne 1 a maximalne 100 znakov" << endl;
}
while( slovo.size() > max)
{
cin >> slovo;
}
for (int i=0; i <= slovo.size(); i++)
{
int s = slovo[i];
while (s > 'A' && s <= 'Z')
{
if(s<='Z' && s>='A'){
return s-('Z'-'_z');
}else{
cout << "chyba";
}
}
}
cout << slovo[i] << endl;
}
}else{
cout << "Minimalne 1 a maximalne 100 uloh" << endl;
}
system("pause");
}
EDIT>
for (int i=0; i <= slovo.size(); i++)
{
while (slovo[i] >= 'A' && slovo[i] <= 'Z')
{
string s = transform(slovo[i]);
cout << s << endl;
s = untransform(s);
cout << s << endl;
}
}
This should work:
#include <string>
#include <cctype>
#include <iostream>
using namespace std;
string
transform(const string& s)
{
const size_t n = s.size();
string t;
for (size_t i = 0; i < n; ++i)
{
const char c = s[i];
if (isupper(c))
{
t.push_back('_');
}
t.push_back(tolower(c));
}
return t;
}
string
untransform(const string& s)
{
string t;
const size_t n = s.size();
size_t i = 0;
while (i < n)
{
char c = s[i++];
if (c != '_')
{
t.push_back(c);
continue;
}
c = s[i++];
t.push_back(toupper(c));
}
return t;
}
int
main()
{
string s = transform("loLollL");
cout << s << endl;
s = untransform(s);
cout << s << endl;
}

Last element added to an array is being added twice, unable to figure out why

Realization: Wow spent so much time staring at this code I finally noticed something I'd been missing all along. I initialize i = size which means at the start the array is looking at an unfilled spot so I finally understand why it always puts a repeat. Now to attempt to fix it. Feel free to berate me.
I'm looking through the array backwards because I'm using an insertion sort algorithm so I work backwards from the last known element to alphabetize the data. However no matter what the final line in the data file (from which I'm reading) it always repeats twice. Here is the array contents printed to demonstrate the repeat:
List of names sorted:
100 bill gates
100 bill gates
65 duck donald
60 frog freddie
71 ghost casper
85 mouse abby
73 mouse mickey
95 mouse minnie
Notice that bill gates is listed twice. The problem appears to be with the way I'm looping. If I modify the lower bound in the loop to 1 instead of 0 then shit goes haywire. Here is the function in question, I don't believe any of the code outside is relevant so I did not include it:
bool sortInput(ifstream &infile, StudentType students[], int &size)
{
StudentType temp;
//empty condition
if(size == 0)
{
infile >> temp.last >> temp.first >> temp.grade;
strcpy(students[0].last, temp.last);
strcpy(students[0].first, temp.first);
students[0].grade = temp.grade;
size++;
}
while(infile)
{
infile >> temp.last >> temp.first >> temp.grade;
if(temp.grade >= LOWGRADE && temp.grade <= MAXGRADE)
{
for(int i = size; i > 0; i--)
{
if(strcmp(temp.last, students[i-1].last) < 0)
{
students[i] = students[i-1];
students[i-1] = temp;
}
else if(strcmp(temp.last, students[i-1].last) == 0 && strcmp(temp.first, students[i-1].first) < 0)
{
students[i] = students[i-1];
students[i-1] = temp;
}
else
{
students[i] = temp;
break;
}
}
size++;
//tester loop to print contents every step of the way
for(int i = 0; i < size; i++)
{
cout << "TEST: " << students[i].last << " " << students[i].first << " " << students[i].grade << endl;
}
cout << "DONE" << endl;
} //end for loop
} //end while loop
return true;
}
However if the full code is necessary for further context then here it is:
// ----------------------------------------------------------------------------
// You write meaningful doxygen comments and assumptions
#include <string.h>
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int const MAXSIZE = 100; // maximum number of records in total
int const MAXLENGTH = 31; // maximum string length
int const MAXGRADE = 100; // highest possible grade
int const LOWGRADE = 0; // lowest possible grade
int const GROUP = 10; // group amount
int const HISTOGRAMSIZE = (MAXGRADE-LOWGRADE)/GROUP + 1; // grouped by GROUP
struct StudentType { // information of one student
int grade; // the grade of the student
char last[MAXLENGTH]; // last name (MAXLENGTH-1 at most)
char first[MAXLENGTH]; // first name (MAXLENGTH-1 at most)
};
// prototypes go here
bool sortInput(ifstream &, StudentType [], int &);
void displayList(StudentType [], int);
void setHistogram(int [], StudentType [], int);
void displayHistogram(int []);
int findAverage(StudentType [], int);
//------------------------------- main ----------------------------------------
int main() {
StudentType students[MAXSIZE]; // list of MAXSIZE number of students
int size = 0; // total number of students
int histogram[HISTOGRAMSIZE]; // grades grouped by GROUP
int average = 0; // average exam score, truncated
// creates file object and opens the data file
ifstream infile("data1.txt");
if (!infile) {
cout << "File could not be opened." << endl;
return 1;
}
// read and sort input by last then first name
bool successfulRead = sortInput(infile, students, size);
// display list, histogram, and class average
if (successfulRead) {
displayList(students, size);
setHistogram(histogram, students, size);
displayHistogram(histogram);
average = findAverage(students, size);
cout << "Average grade: " << average << endl << endl;
}
return 0;
}
bool sortInput(ifstream &infile, StudentType students[], int &size)
{
StudentType temp;
//empty condition
if(size == 0)
{
infile >> temp.last >> temp.first >> temp.grade;
strcpy(students[0].last, temp.last);
strcpy(students[0].first, temp.first);
students[0].grade = temp.grade;
size++;
}
while(infile)
{
infile >> temp.last >> temp.first >> temp.grade;
if(temp.grade >= LOWGRADE && temp.grade <= MAXGRADE)
{
for(int i = size; i > 0; i--)
{
if(strcmp(temp.last, students[i-1].last) < 0)
{
students[i] = students[i-1];
students[i-1] = temp;
}
else if(strcmp(temp.last, students[i-1].last) == 0 && strcmp(temp.first, students[i-1].first) < 0)
{
students[i] = students[i-1];
students[i-1] = temp;
}
else
{
students[i] = temp;
break;
}
}
size++;
for(int i = 0; i < size; i++)
{
cout << "TEST: " << students[i].last << " " << students[i].first << " " << students[i].grade << endl;
}
cout << "DONE" << endl;
} //end for loop
} //end while loop
return true;
}
void displayList(StudentType students[], int size)
{
cout << "List of names sorted:" << endl;
for(int i = 0; i < size; i++)
{
cout << " " << students[i].grade << " " << students[i].last << " " << students[i].first << endl;
}
cout << endl;
}
void setHistogram(int histogram[], StudentType students[], int size)
{
int groupIndex;
for(int i = 0; i < size; i++)
{
groupIndex = (students[i].grade - LOWGRADE) / GROUP;
histogram[groupIndex]++;
}
}
void displayHistogram(int histogram[])
{
cout << "Histogram of grades: " << endl;
int bottomBin = LOWGRADE;
int binWidth = (MAXGRADE - LOWGRADE) / GROUP - 1;
int topBin = bottomBin + binWidth;
for(int i = 0; i < HISTOGRAMSIZE; i++)
{
cout << bottomBin << "--> " << topBin << ": ";
for(int j = 0; j < histogram[i]; j++)
{
cout << "*";
}
cout << endl;
bottomBin += binWidth + 1;
topBin = min(topBin + binWidth + 1, MAXGRADE);
}
}
int findAverage(StudentType students[], int size)
{
int total = 0;
for(int i = 0; i < size; i++)
{
total += students[i].grade;
}
return total / size;
}
// ----------------------------------------------------------------------------
// functions with meaningful doxygen comments and assumptions go here
You can combine the stream extraction and testing the stream state by changing:
while(infile)
{
infile >> temp.last >> temp.first >> temp.grade;
...
}
to
while(infile >> temp.last >> temp.first >> temp.grade)
{
...
}
This will read the stream and fail (return false) if the read fails for any reason, including EOF.
Note: read this related question for more explanation.
End-of-file indicator is set not when the last byte of file is read, but when an attempt is made to read the next byte, the byte that doesn't exist.
Thus, after the last line is read, while(infile) check still succeeds, but infile >> temp.last call fails, leaving the variable intact. You don't check for that failure, so you run one extra iteration of the loop, using values read by the previous iteration.