#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main () {
const int SZ = 5;
string word[SZ];
int len,min,large,max;
for(int i = 0; i < SZ; i++){
cout << "Please Enter a word five times: ";
cin >> word[i];
}
min = word[SZ].length();
for(int i = 0; i < SZ; i++){
if(word[i] < len){ // I'm getting it on this line of code
min = word[i];
}
}
return 0;
}
My code is not properly running and currently I'm trying to find the smallest word of 5 different words inputted by the user.
There are some mitakes in your code:
Your first cout should be above the for loop rather than inside of it.
word[SZ].length() is accessing a string that is out of bounds of the array. You should be accessing the 1st string at word[0] instead.
on the statement if(word[i] < len), len is uninitialized. For that matter, you don't even need len at all, use min instead. But more importantly, you are comparing a string to an int, which is why you are getting an error. You need to compare the string's length() value instead.
Try this:
#include <iostream>
#include <string>
using namespace std;
int main () {
const int SZ = 5;
string word[SZ];
int min, max;
cout << "Please enter " << SZ << " words: ";
for(int i = 0; i < SZ; i++){
cin >> word[i];
}
min = max = word[0].length();
for(int i = 1; i < SZ; i++){
if (word[i].length() < min){
min = word[i].length();
}
if (word[i].length() > max){
max = word[i].length();
}
}
cout << "min: " << min << ", max: " << max << endl;
return 0;
}
Online Demo
For starters, this (modified) statement:
cout << "Please Enter " << SZ << " words: ";
should be placed before the for loop:
for(int i = 0; i < SZ; i++){
cin >> word[i];
}
In this statement:
min = word[SZ].length();
you are using a non-existent element of the array with the index SZ, while the valid range of indices for the array is [0, SZ).
So, rewrite it like:
auto min = word[0].length();
Within the for loop, this statement:
if(word[i] < len)
does not make sense. You need to write:
if(word[i].length() < min)
Also, this statement:
min = word[i];
has invalid operands for the assignment operator.
The loop can look like
auto min = word[0].length();
for( size_t i = 1; i < SZ; i++ ){
if( word[i].length() < min ){
min = word[i].length();
}
}
If you need to find the word with the minimal length then the for loop can look the following way
size_t min = 0;
for( size_t i = 1; i < SZ; i++ ){
if( word[i].length() < word[min].length() ){
min = i;
}
}
Pay attention to that, there is a standard algorithm std::min_element declared in the header <algorithm> that can be used instead of the manually written loop.
Related
so I wrote this code to reverse one of the names based on the user option the idea is to use another function to reverse and to use pointers but after trying all I could think of my code return the same name not changed the best I could do was changing the first letter of the name to a weird sign.
#include <iostream>
using namespace std;
void reverse(char* A) {
int count = 0;
char temp[10];
for (int i = 0; A[i] != NULL; i++)
count++;
for (int i = 0; A[i] != NULL; i++) {
temp[count]=A[i];
count--;
}
for (int i = 0; A[i] != NULL; i++) {
A[i] = temp[i];
}
}
int main(){
int x= 0;
int index;
char Name_list[5][10];
cout << "please enter the names of the student " << endl;
for (int i = 0; i < 5; i++) {
cin >> Name_list[i];
for (int j = 0; Name_list[i][j] != NULL; j++) {
x++;
}
while (x > 10)
{
x = 0;
cout << "you have entered more then the allowed number of characters per name enter another name " << endl;
cin >> Name_list[i];
for (int j = 0; Name_list[i][j] != NULL; j++) {
x++;
}
}
x = 0;
}
for (int i = 0; i < 5; i++) {
cout << Name_list[i] << endl;
}
cout << "please enter the index of the name you want to reverse" << endl;
cin >> index;
while (index>4||index <0)
{
cout << "you entered incorrect index please enter a number from 0 to 4 " << endl;
}
reverse(Name_list[index]);
for (int i = 0; i < 5; i++) {
cout << Name_list[i] << endl;
}
system("pause");
}
For starters such a function should return a pointer to the result string. That is it should be declared like
char * reverse( char *s );
Note: do not use variable names consisting from upper case letters.
The type int can be not large enough to store length of a string. Instead use the type size_t.
char * reverse( char *s )
{
size_t count = 0;
//...
It is totally unclear why there is present an array with the number of elements equal to the magic number 10
char temp[10];
To reverse a string there is no need to declare an auxiliary array. Such an approach is principally wrong.
In this for loop
for (int i = 0; A[i] != NULL; i++)
there is compared an object of the type char with the pointer NULL. The compiler should issue a message for such a wrong comparison. It seems you mean
for (int i = 0; A[i] != '\0'; i++)
In any case the introduced variable i in this first for loop is redundant because you already has the variable count.
As you have the array temp with the fixed size equal to 10 then the both loops after the first loop can invoke undefined behavior even if the length of the source string is equal exactly to 10.
And the result string is not zero terminated.
The function can look the following way.
char * reverse( char *s )
{
size_t count = 0;
while ( s[count] ) ++count;
for ( size_t i = 0; i < count / 2; i++ )
{
char c = s[i];
s[i] = s[count - i - 1];
s[count - i - 1] = c;
}
return s;
}
Or using standard functions you could write the function reverse the following way
#include <utility>
#include <cstring>
//...
char * reverse( char *s )
{
for ( size_t i = 0, n = std::strlen( s ); i < n / 2; i++ )
{
std::swap( s[i], s[n-i-1] );
}
return s;
}
Pay attention to that there is the standard algorithm std::reverse. Using it you could reverse a string the following way
std::reverse( s, s + std::strlen( s ) );
for (int i = 0; A[i] != NULL; i++) {
temp[count]=A[i];
count--;
}
If i goes up from 0 to 5, count goes down from 6 to 1.
Ok, a few things.
If you want do some string manipulation, look into the stdlib. Unless you are doing this for class.
Your writing everything to the end of the temp. buffer
You need to add an extra character at the end of the strings for the null byte (I think this implementation may allow for a seg. fault)
I can't figure it out. What is wrong with my code? I am new to programming.
Program required output: Write a C++ program to find the maximum-occurring character in an array, using a loop.
My code:
#include <string.h>
using namespace std;
void FindMaxChar(char Word[])
{
int count = 0;
int max = 0;
char index = 0;
int length = strlen(Word);
for (int i = 0; i < length; i++)
{
index = Word[i];
for (int j = 0; j < length; j++)
{
if (index == Word[j])
{
count++;
}
}
if (count > max)
{
max = count;
index = Word[i];
}
}
cout << index << " is repeating " << max << " times.";
}
int main()
{
char Word[100] = {0};
cout << "Enter the Word = ";
cin.get(Word,100);
FindMaxChar(Word);
}
My Output:
Enter the Word = caaar
r is repeating 11 times.
You never reset count each loop. So you continue incrementing it but never clear it.
Add count = 0 to the beginning of the outer for loop:
for (int i = 0; i < length; i++)
{
count = 0; // Reset counter
You're also trying to use index for two different purposes. You're both using it to store the current character you're looking at (not an index, kind of confusing that you named it like that), AND the character you've seen the most (still not an index, also confusing).
Instead, you need another variable here.
Also note that if you declare Word as char Word[100], it can only hold a c-string of length 99 (to leave room for the null character). So your cin should actually be:
cin.get(Word, 99);
Thanks to the great people of this community.
I am able to find my error and corrected it.
Correct Code :
#include <iostream>
#include <string.h>
using namespace std;
void FindMaxChar(char Word[])
{
int count = 0;
int max = 0;
char index = 0;
char final = 0;
int length = strlen(Word);
for (int i = 0; i < length; i++)
{
index = Word[i];
count = 0;
for (int j = 0; j < length; j++)
{
if (index == Word[j])
{
count++;
}
}
if (count > max)
{
max = count;
final = index;
}
}
cout << final << " is repeating " << max << " times.";
}
int main()
{
char Word[100] = {0};
cout << "Enter the Word = ";
cin.get(Word,99);
FindMaxChar(Word);
}
I want to create an array of Bitset .Binary Bitset(example "100","1010",etc)
After that I want to input from user and store in the the Bitset .
I have tried the following line but it says error.
#include<bits/stdc++>
using namespace std;
int main()
{
int n,i;
string bit_string;
cin>>n // size of Bitset array.
bitset<8> brr[n];//
for(i=0;i<n;i++)
{
cin>>bit_string;
brr[i](bit_string);
}
return 0;
}
I want to create n Bitset each of size 8 bits.Where n is given by user.
my input is binary string like.
"110010","001110"
please help
The error ocurrs because you are trying to creat a C-style array using n which is not compile-time constant. It's not possible to creat a C-style array without being n known at compile time.
The following is a good way to do what you want
Creat a std::vector<std::bitset<8>> to hold your bitset<8>s, as follows.
Note that the code ignores the excess of characters in strings iput like "111111110" (makes it "11111111") and treats any character except '1' as if it were '0' and if the input string is less than 8 characters, the code adds zeros by the default of the bitsets
#include <vector>
#include <bitset>
#include <iostream>
int main() {
int n, i;
std::string bit_string;
std::cout << "Enter the size";
std::cin >> n; // size of Bitset array.
std::vector<std::bitset<8>> brr(n);//
for (i = 0; i < n; i++) {
std::cin >> bit_string;
for (int j{}; j < bit_string.size() && j < 8; ++j) {
brr[i][j] = (bit_string[j] == '1') ? 1 : 0;
}
}
//To test
for(auto const& el :brr)
{
for(int i{}; i < 8;)
std::cout << el[i++];
std::cout<<"\n";
}
}
See Why is "using namespace std;" considered bad practice?
and
Why should I not #include <bits/stdc++.h>?
For dynamic count of the objects , Please try vector<> instead of array[]
#include<bits/stdc++>
using namespace std;
int main()
{
int n, i;
string bit_string;
cin >> n; // size of Bitset array.
vector<bitset<8>> arr; //size()=>0
arr.resize(n); //size()=>n
for (i = 0; i < n; i++)
{
cin >> bit_string;
bitset<8>& br = arr[i]; //get the i of n
int maxlen = 8;
if (bit_string.size() <= 8)
maxlen = bit_string.size();
else
cout << "warning invalid len " << bit_string.size() << " of " << bit_string << endl;
for (int j = 0; j < maxlen; j++)
{
if (bit_string[j] == '1')
br.set(j, true);
}
//cout << endl << br << endl; //output test
}
return 0;
}
If you still want to use array , please try this way
#include<bits/stdc++>
using namespace std;
int main()
{
int n, i;
string bit_string;
cin >> n; // size of Bitset array.
bitset<8>* arr = new bitset<8>[n];
for (i = 0; i < n; i++)
{
cin >> bit_string;
bitset<8>& br = arr[i]; //get the i of n
int maxlen = 8;
if (bit_string.size() <= 8)
maxlen = bit_string.size();
else
cout << "warning invalid len " << bit_string.size() << " of " << bit_string << endl;
for (int j = 0; j < maxlen; j++)
{
if (bit_string[j] == '1')
br.set(j, true);
}
//cout << endl << br << endl; //output test
}
delete[] arr; //IMPROTAND , delete the array and free memory
return 0;
}
I'm trying to sort my array pairs by int, but my sort is saying 'unable to resolve identifier' to pairs.begin(), pairs.end(), and compare_pairs_second(). I cannot figure out why but i'm probably doing something wrong?
Here is my code:
#include <iostream>
#include <string>
#include <cstdlib>
#include <iomanip>
#include <algorithm>
#include <iterator>
using namespace std;
main()
{
string name[10];//declaring an array name
int number[10];//declaring an array number
cout << "Please input 10 names \n";//output
for(int i = 0; i < 10; i++){//for statement
cin >> name[i];//inputting names in the array names
}
cout << "Please input their corresponding numbers \n";//output
for(int x = 0; x < 10; x++){
cin >> number[x];//inputting numbers
}//end for
int i = 0;//redeclaring i to be 0
int x = 0;//redeclaring x to be 0
for(int l = 0; l < 10; l++)//for statement
{
cout << name[i] << ": " << number[x] << "\n";
i++;//adding 1 to i so outputs all of array name
x++;//adding 1 to x so outputs all of array number
}//end for
pair<string, int> pairs[10];
int i = 0;
int x = 0;
for(int z = 0; z < 10; z++)
{
pairs[z] = make_pair(name[i], number[x]);
i++;
x++;
}
std::sort(pairs.begin(), pairs.end(), compare_pairs_second<std::less>());
int i = 0;
int x = 0;
for(int z = 0; z < 10; z++)
{
name[i] = pairs[z].first;
number[x] = pairs[z].second;
i++;
x++;
}
string search = "";
cout << "Enter a name to search for";
cin >> search;
size_t found = pairs.find(search);
if(found!=string::npos)
cout << search << pairs;
} //end main
UPDATE/EDIT:
I got my sort to work...to an extent. I deleted the line of code that was giving me errors, and it now sorts my number array, which is half of what I wanted. But now how do I keep the names with their respective numbers without using my pairs variable that I had prior to this fix?
Ex
array number[5]={5, 2, 9, 11, 27};
array name[5]={"Steve", "John", "Bob", "Larry", "Patric"};
Output after sorting:
John: 2 Steve: 5 Bob: 9 Larry: 11 Patric: 27
#include <iostream>
#include <string>
#include <cstdlib>
#include <iomanip>
#include <algorithm>
#include <iterator>
using namespace std;
main()
{
const int size = 10;
string name[10];//declaring an array name
int number[10];//declaring an array number
cout << "Please input 10 names \n";//output
for(int i = 0; i < 10; i++){//for statement
cin >> name[i];//inputting names in the array names
}
cout << "Please input their corresponding numbers \n";//output
for(int i = 0; i < 10; i++){
cin >> number[i];//inputting numbers
}//end for
sort(number,number+size);
int i;
int j;
int min;
int counter = 0;
for(i = 0; i < counter; i++)
{
min = i;
for(j = i+1; j < counter; j++)
{
if(name[j] < name[min])
{
string tempString = name[i];
name[i] = name[j];
name[j] = tempString;
int tempInt = number[i];
number[i] = number[j];
number[j] = tempInt;
}
}
}
for(i = 0; i < 10; i++)
{
cout << name[i] << ": " << number[i] << "\n";
};
} //end main
Current output sorts numbers but does not keep names with them.
pairs is raw array, not a STL container; you can't invoke method on it like pairs.begin() and pairs.end().
Since C++11 you could use std::begin() and std::end(), which are overloaded for supporting raw arrays. e.g.
std::sort(std::begin(pairs), std::end(pairs), compare_pairs_second<std::less>());
I was making an app that calculates the mean, median, and range of any integers, but I ran into the issue: Vector subscript out of range. I've looked at some other posts about this, and still haven't been able to fix it.
Here's my code:
#include <iostream>
#include <Algorithm>
#include <Windows.h>
#include <vector>
using namespace std;
int main() {
//Variables
int sze;
int mraw = 0;
double mean;
double median;
double range;
int fullnum = 0;
int lastnum = 1;
vector<int> med;
cout << "How many numbers do you have? ";
cin >> sze;
int *arr = new int[sze];
for (int i = 0; i < sze; i++) {
med.push_back(arr[i]);
}
//Getting numbers
for (int i = 0; i < sze, i++;) {
system("cls");
cout << "Enter number #" << i + 1 << ": ";
cin >> arr[i];
}
//Mean
for (int i = 0; i < sze; i++){
fullnum += arr[i];
}
mean = fullnum / sze;
//Median
sort(med.begin(), med.end());
int mvs = sze;
while (med.size() >= 2) {
med.erase(med.begin());
med.erase(med.begin() + med.size() - 1);
mvs--;
}
if (mvs == 2) {
mraw = med[1] + med[2];
median = mraw / 2;
}
else {
median = mvs;
}
//Range
vector<int> rnge;
for (int i = 0; i < sze; i++) {
rnge.push_back(arr[i]);
lastnum++;
}
sort(rnge.begin(), rnge.end());
int bigsmall[2];
bigsmall[1] = rnge[1];
bigsmall[2] = rnge[lastnum];
range = bigsmall[2] - bigsmall[1];
//Outputs
cout << "Mean: " << mean << "\nMedian: " << median << "\nRange: " << range;
system("cls");
return 0;
}
You have what would be an off-by-one error if lastnum was initialized to 0.
When rnge is empty, presumably lastnum is 0. This means access rnge[lastnum] is in error, as rnge is empty.
Applying an inductive argument shows that lastnum is the count of number of elements, and not the index of the last element. Thus, rnge[lastnum] is always out of range.
In actuality, you have initialized lastnum to 1, so your bug is actually off-by-two.