So there was this question in recent programming contest.
we have a test case in that question
8
11001101
Now the output I want is 1 but this line
cout << s.erase(0,6) << "\n"
gives 01 even though i want to remove elements from 0 to 6th index position.
How should i remove elements from 0 to 6 (including 6)
Here is the code for reference
#include <vector>
#include <iostream>
using namespace std;
int main(){
int t; cin >> t;
while(t--){
long n; cin >> n;
string s; cin >> s;
int index_l=0;
int index_r=0;
for(int i=0;i<n;i++){
if(s[i]=='1'){
index_l = i;
break;
}
}
for(int i=s.length(); i > index_l;i--){
if(s[i] == '0'){
index_r = i;
break;
}
}/*
cout << s.length() << "\n";
cout << index_l << " " << index_r << "\n";
*/
if(index_r == 0) cout << s << "\n";
else cout << s.replace(index_l,index_r,"0");
}
return 0;
}
Look at some documentation for std::string::erase. There's an overload that takes a starting index and a count of characters to remove. If you want to erase the first 7 characters then you should do:
s.erase(0, 7)
Just to be clear, the second parameter isn't a position. It's the number of characters to remove.
Related
i tried to separate even and odd numbers using vectors from a array ==>
so i made a function that returns true is number is even and false for if number is odd
then i used an if else statement where if the function returns true then it pushbacks the value in a vector and if the function returns false then it pushbacks the value in another vector , finally i printed all the elements in the vector but the output does not show any element except it shows one in the odd vector.
#include <iostream>
#include <vector>
using namespace std;
bool sort(int arr[] , int i){
if(arr[i] %2 == 0){
return true;
}
return false;
}
int main(){
int n;
cin >> n;
int *arr = new int[n];
for(int i=1 ; i<=n ; i++){
arr[i-1] = i;
}
vector <int> even , odd;
int i=0 ;
if(sort(arr , i)){
even.push_back(arr[i]);
sort(arr , i+1);
}else{
odd.push_back(arr[i]);
sort(arr,i+1);
}
cout << "the even numbers are : " << endl;
for(auto element:even){
cout << element << " ";
}
cout << endl;
cout << "the odd numbers are : " << endl;
for(auto element:odd){
cout << element << " ";
}
}
As #TonyDelroy said, you have to make for loop around call to sort(arr, i). Also first loop should go up to i <= n instead of i < n.
Your fixed working code below (see also std::partition_copy variant afterwards):
Try it online!
#include <iostream>
#include <vector>
using namespace std;
bool sort(int arr[] , int i){
if(arr[i] %2 == 0){
return true;
}
return false;
}
int main(){
int n;
cin >> n;
int *arr = new int[n];
for(int i=1 ; i<=n ; i++){
arr[i-1] = i;
}
vector <int> even , odd;
for (int i = 0; i < n; ++i)
if (sort(arr, i))
even.push_back(arr[i]);
else
odd.push_back(arr[i]);
cout << "the even numbers are : " << endl;
for(auto element:even){
cout << element << " ";
}
cout << endl;
cout << "the odd numbers are : " << endl;
for(auto element:odd){
cout << element << " ";
}
}
Input:
10
Output:
the even numbers are :
2 4 6 8 10
the odd numbers are :
1 3 5 7 9
As #chris said you can also use std::partition_copy to implement your algorithm:
Try it online!
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
int n = 0;
std::cin >> n;
std::vector<int> arr(n), odd, even;
for (int i = 1; i <= n; ++i)
arr[i - 1] = i;
std::partition_copy(arr.cbegin(), arr.cend(),
std::back_insert_iterator(odd), std::back_insert_iterator(even),
[](auto const & x){ return (x & 1) == 1; });
std::cout << "the even numbers are : " << std::endl;
for (auto element: even)
std::cout << element << " ";
std::cout << std::endl << "the odd numbers are : " << std::endl;
for (auto element: odd)
std::cout << element << " ";
}
Input:
10
Output:
the even numbers are :
2 4 6 8 10
the odd numbers are :
1 3 5 7 9
You only push one element - the first.
Your partitioning code is equivalent to
if(sort(arr , 0)){
even.push_back(arr[0]);
sort(arr , 1);
}else{
odd.push_back(arr[0]);
sort(arr,1);
}
You need to loop over all the input numbers.
You can also simplify matters with a more generally useful evenness function that doesn't depend on an array:
bool is_even(int x) { return x % 2 == 0; }
and then there is no need to store all the inputs before processing them:
int main(){
vector <int> even , odd;
int n;
cin >> n;
for (int i = 0; i < n; ++i) {
int x;
cin >> x;
if (is_even(x)) {
even.push_back(x);
}
else {
odd.push_back(x);
}
}
cout << "the even numbers are : " << endl;
for (auto element:even){
cout << element << " ";
}
cout << endl;
cout << "the odd numbers are : " << endl;
for (auto element:odd){
cout << element << " ";
}
}
Hye, Im a beginner trying to learn C++ language. This is my code that I tried to find reverse input numbers using array. Can help me point my mistakes since I always got infinite loop.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const int ARRAY_SIZE=50;
int size[ARRAY_SIZE];
unsigned short int i;
cout << "You may enter up to 50 integers:\n";
cout << "\nHow many would you like to enter? ";
cin >> size[ARRAY_SIZE];
cout << "Enter your number: \n";
for (int i = 0; i < ARRAY_SIZE; i++)
{
cin >> size[i];
}
cout << "\nYour numbers reversed are:\n";
for (i = size[ARRAY_SIZE] - 1; i >= 0; i++)
cout << " size[i]" << " ";
}
Your infinite loop is because i is unsigned, so i >= 0 is always true.
Here's a C++-ified version:
#include <iostream>
#include <vector>
int main() {
std::cout << "You may enter up to 50 integers:\n";
std::cout << "\nHow many would you like to enter? ";
int count;
std::cin >> count;
// Use a std::vector which can be extended easily
std::vector<int> numbers;
for (int i = 0; i < count; ++i) {
std::cout << "Enter your number: \n";
int v;
std::cin >> v;
// Add this number to the list
numbers.push_back(v);
}
std::cout << "\nYour numbers reversed are:\n";
// Use a reverse iterator to iterate through the list backwards
for (auto i = numbers.rbegin(); i != numbers.rend(); ++i) {
// An iterator needs to be de-referenced with * to yield the value
std::cout << *i << " ";
}
std::cout << std::endl;
return 0;
}
There's many problems in your original code, but the clincher is this:
for (i = size[ARRAY_SIZE] - 1; i >= 0; i++)
cout << " size[i]" << " ";
}
Since you keep adding to i through each cycle you'll never go below zero, especially not for an unsigned short int. This should be:
for (int i = count - 1; i > 0; --i) {
std::cout << numbers[i];
}
Presuming you have a thing called numbers instead of the bizarrely named size and the array size is count, not i, as i is generally reserved for iterators and loop indexes.
The user inputs some desired length of a string of characters . then the program outputs a list of randomly generated characters. After which the user is prompted to input 2 characters (that either exist or does not exist whiten the list). the program will then output where the first character appears in the pair or say that the pair does not exist in the list.
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
int main()
{
int size, c;
char ltr1, ltr2;
cout << "How many letters do you want in your random sting? ";
cin >> size;
string str;
for (int i = 0; i < size; i++)
{
c = rand() % 26 + 'a';
str.push_back(c);
}
for (int i = 0; i < size; i++)
{
cout << str[i];
}
cout << endl << endl;
cout << "what pair of letters would you like to find?";
cin >> ltr1;
cin >> ltr2;
cout << endl;
for (int i = 0; i < size; i++)
{
if (char((str[i] == ltr1) && (str[i + 1] == ltr2)))
{
cout << "the pair is in the string starting at character number "
<< i << " in the string" << endl;
}
if (char((str[i] == ltr1) && (str[i + 1] != ltr2)))
{
cout << "the pair " << ltr1 << ltr2 << " is not in the string." << endl;
}
}
return 0;
}
the output is capable of determining weather or not the pair exist or not and will output the location however if you input a value greater than 25 it will run the final output multiple times.
This question already has answers here:
How to make cin take only numbers
(2 answers)
Closed 6 years ago.
So the requirements for this program is to be able to increment arrays of the same size (size from 5 to 15 indexes) and increment each element in the array by one using for and while loops. The last task is to take values from the first array and put them in reverse order and assign them to the second array.
So everything works as normal, and the program rejects invalid inputs and does not go into an infinite loop. However, the program accepts some inputs that are not wanted.
For example, I would input something like '12 a' or '7 asdfkla;j lasnfg jasklgn asfg' and it would go through. It is interesting too because the code registers only 12 or 7 and completely ignores the rest. I think it is because once it hits a non-integer character, it would stop ignore the rest.
Why is it ignoring the rest of the input? And is there a way to catch this error from going through?
Also, if you see anything that catches your eye, feel free to critique c: I am always looking to improving.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand(time(NULL));
int x;
int j = 0;
bool not_valid = true;
system("color f");
cout << "Program will ask for an input for the size of an array.\n"
<< "With the array size defined, program will generate semi-\n"
<< "true random integers from 0 to 8. First array will then\n"
<< "be assigned to the second in reverse (descending) order.\n\n";
do {
cout << "Enter array size (0 - 15): ";
cin >> x;
if (x >= 5 && x <= 15) {
not_valid = false;
cout << "\nArray size: " << x << endl;
}
else {
cout << "Invalid input.\n\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
} while (not_valid);
int *arr0;
int *arr1;
arr0 = new int[x];
arr1 = new int[x];
for (int i = 0; i < x; i++) {
arr0[i] = rand() % 9;
}
for (int i = 0; i < x; i++) {
arr1[i] = rand() % 9;
}
cout << "\nARRAY 0 (unmodified, for):\n";
for (int i = 0; i < x; i++) {
cout << arr0[i] << "\t";
}
cout << "\n\nARRAY 0 (modified, for):\n";
for (int i = 0; i < x; i++) {
arr0[i]++;
cout << arr0[i] << "\t";
}
cout << "\n\nARRAY 1 (unmodified, while):\n";
for (int i = 0; i < x; i++) {
cout << arr1[i] << "\t";
}
cout << "\n\nARRAY 1 (modified, while):\n";
while (j < x) {
arr1[j]++;
cout << arr1[j] << "\t";
j++;
}
int second = x - 1;
for (int i = 0; i < x; i++) {
arr1[second] = arr0[i];
second--;
}
j = 0;
cout << "\n\nARRAY 1 (array 0, descending):\n";
while (j < x) {
cout << arr1[j] << "\t";
j++;
}
cout << endl << endl;
system("pause");
return 0;
}
Take input in string and then check if it's a number or not.
Example:
#include<iostream>
#include<sstream>
#include <string>
using namespace std;
int main()
{
string line;
int n;
bool flag=true;
do
{
cout << "Input: ";
getline(cin, line);
stringstream ss(line);
if (ss >> n)
{
if (ss.eof())
{
flag = false;
}
else
{
cout << "Invalid Input." << endl;
}
}
}while (flag);
cout << "Yo did it !";
}
Question: why does it print out the correct values inside the while loop (while reading / inputting the file) but not outside the while loop? I don't understand.
Thank you very much for any help.
input file:
1
2
3
4
5
#include <iostream>
#include <string>
#include <fstream>
#include <string>
using namespace std;
int sumNumbers(int sum, int* numbers, int numElements, int count)
{
if (count == numElements) return sum;
sumNumbers(sum + numbers[count], numbers, numElements, count + 1);
return 0;
}
int main(int argc, char* argv[])
{
int* numbers;
int numElements = 0;;
int sum = 0;
string fileName = argv[2];
ifstream ifile(fileName);
if( ifile.fail() ) {
cout << "The file could not be opened. The program is terminated." << endl;
return 0;
}
while ( !ifile.eof() ) {
numbers = new int[++numElements];
ifile >> numbers[numElements - 1];
cout << "Position " << numElements - 1 << ": " << numbers[numElements - 1] << endl;
}
cout << numbers[0] << endl;
cout << numbers[1] << endl;
cout << numbers[2] << endl;
cout << numbers[3] << endl;
cout << numbers[4] << endl;
cout << "--------------\n";
for(int i = 0; i < numElements; i++) {
cout << "Position " << i << ": " << numbers[i] << endl;
}
sumNumbers(sum, numbers, numElements, 0);
cout << "The sum of the numbers in the file is: " << sum << endl;
return 0;
}
output:
Position 0: 1
Position 1: 2
Position 2: 3
Position 3: 4
Position 4: 5
0
-805306368
0
-805306368
5
--------------
Position 0: 0
Position 1: -805306368
Position 2: 0
Position 3: -805306368
Position 4: 5
The sum of the numbers in the file is: 0
You are instantiating (and leaking) a new array in each loop iteration. And you only fill one element of that array. After the loop ends, you are left with the final array, with only the last element set.
There are many questions on SO that deal with the problem of reading numbers from a file into an array or container. Here, numbers are read into an std::vector.
#include <fstream>
#include <vector>
#include <iterator>
#include <iostream>
#include <algorithm>
int main()
{
std::vector<int> numbers;
ifstream ifile(fileName);
std::istream_iterator<int> eof;
std::istream_iterator<int> it(ifile);
std::copy(it, eof, std::back_inserter(numbers));
for(int i = 0; i < numbers.size(); ++i)
{
cout << "Position " << i << ": " << numbers[i] << endl;
}
}
Alternatively, you can replace the istream_iterators and the call to std::copy by a while loop:
int n=0;
while (ifile >> n) {
numbers.push_back(n);
}
This part:
while ( !ifile.eof() ) {
numbers = new int[++numElements];
// ...
repeatedly allocates memory for numbers. At each new, previous values are lost, and the memory from the previous allocation is leaking. You can print the value correctly before the next call to new so it seems to work within the loop.
It is better to use a vector:
int new_number;
while ( ifile >> new_number) {
numbers.push_back(new_number);
// ...
and don't use file.eof() in the while condition.