Comparing an element of a string array with a string - c++

So, while practicing strings i came across this question that gave me, "n" number of strings and it asked me to output strings in increasing alphabetical order.
Example :
Input>>
4 // number of string
abcdef ghi // string 1
ccdef // string 2
bcdcas // string 3
xcxvb // string 4
vxzxz // string 5
This will output only strings 1,2,4 because we have to print string in an increasing alphabetical way.
string 1 < string 2 < string 4.
(string 3 is smaller than string 2, and hence the output)
So i coded the problem without using string array and it worked, but when i applied the same approach the output was not correct.
Maybe i don't know something about string array that you guys can help me with.
Here is the code for you guys :
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
int n;
cin >> n;
string array[n];
cin.ignore();
for(int i=0; i<n;i++){
getline(cin , array[i]);
}
cout << array[0] << endl;
string maximum;
for(int i = 0; i<n; i++){
maximum = array[0];
if(array[i] > maximum){
maximum = array[i];
cout << maximum << endl;
}
}
}
Here is the code that worked without any problems:
using namespace std;
int main()
{
ios::sync_with_stdio(false);
int n;
cin >> n;
string text;
cin.ignore();
string max = "";
for(int i=0; i<n;i++){
getline(cin , text);
if(text>max){
max = text;
cout << text << endl;
}
}
}

I've used your working code as a starting point. Try to avoid c-style arrays and use one of the C++ containers (like std::vector) instead.
#include <iostream>
#include <string>
#include <vector>
int main()
{
int n;
std::string text;
std::vector<std::string> array;
std::cout << "Enter number of strings: ";
std::cin >> n;
std::cin.ignore();
for(int i=1; i<=n;i++) {
std::cout << "Enter string " << i << ": ";
std::getline(std::cin, text);
// check if we already have stored anything in the array and
// then check if text is <= than the last element in the array.
// if so, continue will skip to the next iteration in the for-loop
if(array.size()>0 && text<=array.back()) continue;
std::cout << "saved " << text << "\n";
array.emplace_back(std::move(text));
}
std::cout << "All saved strings:\n";
for(auto& s : array) {
std::cout << s << "\n";
}
}

Related

C++ String input in Vector [duplicate]

This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 1 year ago.
I want to input multi-word strings into vector "name". Using cin works fine for single word inputs.
What i want is :
Take number of string inputs from the user. for example : "Random Name"
Store all the String value into the vector names
Here is the code i wrote
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<string> names;
string user;
int n;
cout << "Enter number of Users : ";
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> user;
names.push_back(user);
}
for (int i = 0; i < names.size(); i++)
{
cout << names[i] << " ";
}
}
Problem:
When i use getline() instead of cin in the for loop, it omits 1 input.
For example , if the user inputs - Number of Users = 3, it only takes 2 string inputs
string user[n]; // value of n given by user using cin
for (int i = 0; i < n; i++)
{
getline(cin, user[i]);
names.push_back(user[i]);
}
Try this:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<string> names;
string user;
int n;
cout << "Enter number of Users : ";
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> std::ws;
getline(cin,user);
names.push_back(user);
}
for (int i = 0; i < names.size(); i++)
{
cout << names[i] << " ";
}
}
cin>>std::ws;
The issue here is that the compiler is considering the newline after you are entering the number of inputs, and pressing enter. So, the fix is to extract the additional whitespaces. Check http://www.cplusplus.com/reference/istream/ws/

sort and show the number of digits

I want to my program can sort the inputted integer and compute the number of any integer that inputted and I don't know where should write the cout of c
example
a[9]={2,3,2,6,6,3,5,2,2}
the number of 2 is 4
the number of 3 is 2
the number of 6 is 2
.
.
please fix this code
int main()
{
cout << "please enter the number of digites :" << endl;
int n;
cin>>n;
int a[n];
cout<<"enter numbers :"<<endl;
for(int i=0;i<n;i++)
cin>>a[i];
int i,j;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
if(a[j]>a[j+1])
{
int temp;
temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
int c;
for(int m=0;m<n;m++)
{
if(a[m]==a[m+1])
c++;
else
c=0;
}
return 0;
}
Read through my solution, I've commented the parts I've changed. I tidied it up a little.
To answer your question: you should print the output (frequency of an integer in array) before you reset the count variable to 1. This will work because we have sorted the array, and will not have to look ahead for more occurrences of the current number.
[EDIT] I also added this above your code:
#include <iostream>
#include <vector>
using namspace std;
Full Solution
#include <iostream>
#include <vector>
using namespace std;
int main() {
// Get input
int n;
cout << "Please enter the number of digits: ";
cin>>n;
vector<int> a;
cout << "Enter " << n << " numbers: " << endl;
for(int i=0;i<n;i++) {
int temp;
cin >> temp;
a.push_back(temp);
}
// Sort input
int i,j;
for (i = 0; i < a.size(); i++) {
for(j = 0; j < a.size()-i-1; j++) {
if(a[j] > a[j+1]) {
int temp;
temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
}
// If an element is in an array
// we can not have 0 occurrences
// of that element, hence count
// must start at 1
int count = 1;
// Int to count
int current = a[0];
// Ouput if we have reset the count,
// or if it is the last iteration
bool output;
// Loop through array
for (int i = 1; i < a.size(); i++) {
output = false; // Reset output if we have printed
if (a[i] == current) {
// If current int and the element next to it are the same,
// increase the count
count++;
} else {
// If current and next are different,
// we need to show the frequency,
// and then reset count to 1
cout << current << " occurs " << count << " times" << endl;
count = 1;
current = a[i];
}
}
// Output one last time, for last int in sorted set
cout << current << " occurs " << count << " times" << endl;
return 0;
}
If this doesn't help, go and read this page, it is a solution in C, but can be adapted to C++ easily. https://codeforwin.org/2015/07/c-program-to-find-frequency-of-each-element-in-array.html This will help you understand and write the task. They take you step-by-step through the algorithm.
This is a typical use-case for a std::map. A std::map<char,int> lets you easily count the frequency of charaters (its easier to treat the user input as characters instead of converting it to numbers).
This is basically all you need:
#include <iostream>
#include <iterator>
#include <map>
int main(){
std::istream_iterator<char> it( std::cin );
std::istream_iterator<char> end_of_input;
std::map<char,int> data;
while (it != end_of_input ) data[*(it++)]++;
for (const auto& e : data) std::cout << e.first << " " << e.second << "\n";
}
This is probably a lot at once, so lets go one by one.
std::istream_iterator<char> lets you extract characters from a stream as if you are iterating a container. So the while iteratates std::cin until it reaches the end of the input. Then *(it++) increments the iterator and returns the character extracted from the stream. data[x]++ accesses the value in the map for the key x and increments its value. If there is no value in the map yet for the key, it gets default initialized to 0.
For input: 11223 it prints
1 2
2 2
3 1
Your code has some issues, not sure if I can catch them all...
You are using VLA (variable lenght arrays) here: int a[n];. This is a compiler extension and not standard c++.
You access the array out of bounds. When i == 0 then j goes up to j<n-i-1 == n-1 and then you access a[j+1] == a[n], but the last valid index into the array is n-1. Same problem in the other loop (a[m+1]).
Assuming your sorting works, the last loop almost gives you the number of elements, but not quite, to fix it you can change it to...
int current = a[0];
int counter = 1;
for(int m=1;m<n;m++) {
if(a[m] == current) {
counter++;
} else {
std::cout << current << " appears " << counter << " times" << endl;
counter=1; // note: minimum freq is 1 not 0
current = a[m];
}
}

Reading integers into an array C++

I'm trying to read a file called numbers.txt and insert the integers into an array. My code outputs only the last integer in the file.
//numbers.txt
1
10
7
23
9
3
12
5
2
32
6
42
My code:
int main(){
ifstream myReadFile;
myReadFile.open("/Users/simanshrestha/Dev/PriorityQueue/PriorityQueue/numbers.txt");
char output[100];
int count = 0;
if (myReadFile.is_open()) {
while (!myReadFile.eof()) {
myReadFile >> output;
//cout<< output << endl;
count++;
}
for(int i=0;i<count;i++)
{
cout << output[i];
}
cout<<endl;
}
cout << "Number of lines: " << count<< endl;
myReadFile.close();
return 0;
}
int main()
{
std::ifstream myReadFile;
myReadFile.open("/home/duoyi/numbers.txt");
char output[100];
int numbers[100];
int count = 0;
if (myReadFile.is_open())
{
while (myReadFile >> output && !myReadFile.eof())
{
numbers[count] = atoi(output);
count++;
}
for(int i = 0; i < count; i++)
{
cout << numbers[i] << endl;
}
}
cout << "Number of lines: " << count<< endl;
myReadFile.close();
return 0;
}
try this.
atoi is a function Convert a string to an integer.
you can try this also: same as the bottom
basically you need to define a "temp" or holder variable to store your data. and anything inside a loop stays in that loop cause of scope resolution, and overriding data each time you store it since it doesn't exit at all.
Hope this helps!
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
const string FILE = "your file name here";
int main()
{
ifstream myReadFile;
myReadFile.open(FILE);
char output[100];
int numbers[100];
int count = 0;
if (myReadFile.is_open()){
while (myReadFile >> output && !myReadFile.eof()) //not stopping until we reach end of file
{
numbers[count] = atoi(output); //converts string to int
count++;
}
for(int i = 0; i < count; i++)
{
cout << numbers[i] << endl;
}
}
cout << "Number of lines: " << count+1 << endl; //total number of lines in file
myReadFile.close();
else{ cout << "Error: File name not loaded" << endl;}
return 0;
}
May I hazard a guess that your code is getting the sum of all the numbers and it is saved in the 1st element of your array?
May I also guess you want the number of the first line in the text file to be saved in the first element of the array? 2nd line in 2nd element so on and so forth?
If so, the following code might need updating:
myReadFile >> output;
to
myReadFile >> output[count];
I'm quite sure this will work in C and assume this would work in C++ too
updated:
another thing to add is to have 2D array like this:
char output[100][5]; //assuming our number is at most 5 char long

c++: how to use char / string 2d array to accept more than 1 sentense from an user?

Below code failed:
#include <iostream>
#include <string>
using namespace std;
int main(){
int a, b;
cout << "how many input you want to give ? ";
cin >> a;
b = a - 1;
string str[b];
for(int i = 0; i <= b; i++){
cout << "Enter a string: ";
getline(cin, str[i]);
}
for(int k = 0; k < a; k++){
cout << "You entered: " << str[k] << endl;
}
return 0;
}
But if I fix the value of 'int a' then the code is running. please help.
Arrays must have a constant size at compile-time so to create an array with dynamic size you can create it on the heap using keyword new and delete[] to free up memory.
Also what is the point in:
cin >> a;
b = a - 1; //?
You can easily do it like this:
int n;
cout << "how many input you want to give ? ";
cin >> n;
string* str = new string[n];
for(int i = 0; i < n; i++){
cout << "Enter a string: ";
getline(cin, str[i]);
}
for(int k = 0; k < n; k++){
cout << "You entered: " << str[k] << endl;
}
Don't forget to clean when you're done:
delete[] str;
You'll want to clear the input buffer, the newline from "How many input you want to give ?" is being fed into the first "Enter a string:".
Add this line after cin>>a;
cin.ignore(INT_MAX, '\n');
Use a vector to store the input.
#include <vector>
#include <string>
#include <iostream>
using names pace std;
int main ()
{
vector <string> input;
string tmp;
while (getline(cin, tmp))
input.push_back(tmp));
for(auto s : input)
cout << s << '\n';
}

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?