Number of substrings starting and ending with '1' [duplicate] - c++

This question already has answers here:
Getline keeps on getting newline character. How can I avoid this?
(7 answers)
Closed 2 years ago.
I'm trying to find the number of substrings that start and end with '1' where input string are numbers like 1111, 10001 etc. Given code does not show correct output but if I replace getline with cin as the input method the code works fine. It also works if I skip input of n (n is the length of the string to be entered) and use i<str.length() in for loop. Why does this happen?
#include <iostream>
#include <string>
using namespace std;
int main(){
int n;
cin>>n;
string str;
getline(cin,str);
int c=0;
for(int i=0;i<n;i++)
if(str[i]=='1')
c++;
c=c*(c+1)/2;
cout<<c;
return 0;
}

This is because getline reads all characters after n until the end of the line including spaces. So the length of your str will be equal to n+1 because of the space in the beginning.
How to fix (for example): for(int i = 1; i < n + 1; i++)

Possible issues with the shared code are:
Collecting input in variable ‘n’ first and then assigning it to a string variable via getline() seems redundant. The expected work can be done with the usage of single getline() statement : “getline(cin,str);”
The usage of variable ‘n’ in the for loop: the variable ‘n’ is to get the length of the input string (so that the loop can compare all elements of the string with number ‘1’. as per the shared code you are trying to execute the for loop for ‘n’ numbers of time which I believe is not the expectation here.)
e.g: if the string input is “111”, then the loop will get executed for 111 times where it should run for 3 times (please correct if my understanding of the motive of the code is different here 😊)
Present loop condition check will surely give the “string subscript out of range” assertion failure.
int n;
cin >> n;
string str;
getline(cin, str);
int c = 0;
for (int i = 0; i < n; i++)
{ }
As per my understating , above code lines can be replaced by below chunk of code.
string str;
getline(cin, str);
int c = 0;
int n = str.size();
for (int i = 0; i < n; i++)
{}

Related

why I am getting i at the end of char array?

#include<iostream>
#include<string.h>
using namespace std;
int main() {
int n;
cin>>n;
char code[n];
cin.ignore();
cin.getline(code, n);
int j=0;
for(int i=0; i<n; i++) {
if((code[i]>='A' && code[i]<='Z') || (code[i]>='a' && code[i]<='z')) {
code[j] = code[i];
j++;
}
}
code[j] = '\0';
cout<<code;
return 0;
}
input :
10
Ajith##
Expected output :
Ajith
Acutal output I'm getting :
Ajithi
why I am getting i at end of array ?
I need to print only alphabets ignoring numbers and special symbols. please help me on this
You tell the program that the input will be ten characters, including null-terminator.
Then you input only seven characters. With the null-terminator that leaves two uninitialized elements of the array, and those two elements will have indeterminate values.
Your loop still uses all ten characters, and using indeterminate values in any way leads to undefined behavior.
What is likely happening is that there's some data after the null-terminator that your program believes is characters.
The solution is std::string and only iterating over the actual length of the string, copying to another std::string.

I am writing a code for palindrome for integer, Why are my strings not comparing to be equal even when they are the same

1.Palindrome code using strings
#include<iostream>
using namespace std;
int main()
{
int t,n;
cin>>t;
while(t--)
{
cin>>n;
string num=to_string(n);
string rev;
//Reversed the string using for loop
for(int i=num.length();i>=0;i--)
{
rev+=num[i];
}
//Checking the strings if they are same
cout<<num<<" "<<rev<<endl;
if(num.compare(rev)==0)
cout<<"wins";
else
cout<<"loses";
}
return 0;
}
2.Output for n=101
101 101
loses
I tried to string method on a separate integer and compare it with other string and it worked.
I don't understand why is the compare method not returning 0.
You access num out of bounds since i = num.length() points at one character passed the last character in the string. It therefore access the terminating \0 character and that's the first character you'll copy and that's why the strings won't match.
Possible correction:
for(size_t i = num.length(); i--;) {
rev += num[i];
}
An alternative, less error prone, solution would be to create rev by using reverse iterators from num:
std::string rev(num.rbegin(), num.rend());

string is not printing in c++ outside the a for loop

I've tried to separate A-Z character in a given string using c++ but the separated string is not printing in the output but if I shift the "cout" statement inside the for loop it printing the characters. I don't know why its happen. please let me know if I've done any mistake.
my code
#include<iostream>
using namespace std;
int main()
{
int t;
cin>>t; //number of test cases
while(t--)
{
string s,a,n;
int j=0,k=0;
char temp;
cin>>s; //getting string
for(int i=0; i<s.length(); i++)
{
if(s[i]>=65 && s[i]<=90) //checking for alphabets
{
a[j]=s[i];
j++;
cout<<a[j-1]<<endl;
}
else
{
n[k]=s[i];
k++;
cout<<n[k-1]<<endl;
}
}
cout<<endl<<a<<endl<<n; //this line is not printing
}
}
String a is empty after initialization (i.e. it has length 0). So you can't access/write any character using a[j], because this writes beyound the string's current bounds and yields undefined behaviour.
use...
a.push_back(s[i]);
to append a character at the end of the string.
Since a is empty at the beginning and, as other answer says, you are writing beyond the string's current bounds, you can resize it to the size of s by doing the following:
a.resize(s.size());
and, once you are done with the work, reduce its capacity to fit the actual size:
a.shrink_to_fit();
This way you won't have memory reallocations that you might have when using std::string::push_back.
Also, you can use isupper() function in your first if condition.
But first you have to initialize s[i] into char variable at first for loop and add #include<cctype> library. Like this:
char c = s[i];
if(isupper(c)){code}

C++: If I want to enter a series of number into an array without being limited by the amount of number I need to enter. How should I do this?

int A[10]
for (int i=0; i< 10; i++){
cin >> A[i] ;
}
I want the users to be able to enter a list of numbers, but right now I have to type in 10 numbers to break the loop. How can I make it so I can stop whenever I want?
I'm a beginner and I am thankful for your time and help!
Than you should use a vector, your array will resize while you push back.
std::vector<int> name;
You can find more about it here
Otherwise you will have to make a function to resize...Vector basically does the same thing for you.
Your code would be than:
int input;
std::vector<int> A;
for (int i=0; i< 10; i++){
cin >> input;
A.push_back(input);
}
To break the loop you could ask a question for the user to break the loop and based on the answer you could break the loop.
you can write the following commands:
int data;
int i =0;
while(cin>>data && i!=10){
arr[i++] = data;
}
Here cin>>data will take input from the file until the file ends.
You can change it to
cin>>data!=-1
where this command will stop taking integer values from the user when they enter -1.

Why do I get random numbers after the input?

I'm trying to take in some input and find the number of a certain character in a string. I keep getting a weird answer when I try to take in the actual string. Why is this happening?
I'm using cout to find why I'm getting such weird numbers and it appears to be a problem with the input.
Note - This is my attempted solution to Codeforces Problem 462 B. I'm attempting to just find the number of a certain letter in the input. My friend is attempting a bubble sort method.
Input:
6 4
YJSNPI
Expected Output:
YJSNPI
4
Actual Output:
YJSNPI
1699623981
Code:
#include <iostream>
#include <string>
#include <vector>
#include <istream>
using namespace std;
int main()
{
int n, k, counting;
cin >> n >>k;
char trash;
cin.get(trash);
vector<string> cards;
string theline, name;
cin >> theline;
cout << theline << "\n";
for (int i = 0; i < n; i++){
name = theline[i];
cards.push_back(name);
}
for (int i = 0; i < n; i++){
if (cards[i] == cards[k-1]){
counting++;
}
}
int tmp = 0;
if (cards.size() != k){
tmp = k - counting;
}
counting *= k;
counting += tmp;
cout << counting;
return 0;
}
Local variables are not automatically initialized to 0. If you try to use the value of a local variable before assigning it, you get undefined behavior. You're incrementing counting without ever initializing it. Change to:
int n, k, counting = 0;
The issue is that the variable "counting" is never initialized - handy link
Basically, "counting" has some garbage value from memory after you declare it with
int counting;
Then, the first operation performed is
counting++;
And the garbage value is saved.
THE FIX:
Change
int counting;
to
int counting = 0;
NOTE: n and k are not helpful variable names. It would make understanding the code a lot easier if they had real names, but oh well.
ADDITIONALLY:
As chris mentioned above, make the compiler work for you. See comment below for good compiler flags. Don't ignore warnings!
Can't really understand what you are doing here. But I can see where you are going wrong.
int n, k, counting;
counting is uninitialized try
int n, k, counting = 0;
I get answer of (1*4 + 4 - 1) = 7 not the 4 you are expecting.
This code will always result in counting = 1, given that k is within range.
for (int i = 0; i < n; i++){
if (cards[i] == cards[k-1]){
counting++;
}
}
https://ideone.com/7Hk3ix