Run-Time Check Failure #2 - s for array of C-Strings - c++

I have the following two 2D Arrays of C-Strings. I am trying to copy the first one onto the second using strcpy() function. However, I keep getting the runtime error.
#define _CRT_SECURE_NO_WARNINGS
#include <cstring>
#include <iostream>
using namespace std;
int main() {
char word1[3][3] = { "Hello", "Bonjour", "Ni Hao" };
char word2[3][3] = { "Steve", "Pei", "Frank" };
char temp[] = "";
for (int i = 0; i < 3; i++) {
strcpy(temp, word1[i]);
strcpy(word1[i], word2[i]);
strcpy(word2[i], temp);
}
for (int i = 0; i < 3; i++) {
cout << word2[i] << " ";
}
cout << endl;
}

In your code i find several mistake.
your char array word1,word2,temp isn't initialize properly.you need to increase size of array.
in loop you use 3.it will break your output if your word's length become grater than 4.
So here i give you little solution.But its better use user input as a size of array so that any input can match properly.
#define _CRT_SECURE_NO_WARNINGS
#include <cstring>
#include <iostream>
using namespace std;
int main() {
char word1[10][10] = { "Hello", "Bonjour", "Ni Hao" };//increase array size to fit word
char word2[10][10] = { "Steve", "Pei", "Frank" };//same here
char temp[10] = "";//same here
for (int i = 0; i < 10; i++) {
strcpy(temp, word1[i]);
strcpy(word1[i], word2[i]);
strcpy(word2[i], temp);
}
for (int i = 0; i <10; i++) {
cout << word2[i] << " ";
}
cout << endl;
}

Related

Can I print the whole array in cpp instead of address [duplicate]

I am trying to print a text file out on screen using arrays, but I'm not sure why it does not appear the way it is in the text file.
The text file:
1 2 3 4
5 6 7 8
Displayed on the screen as follows after applying discard function:
1
2
3
4
5
6
7
8
The code:
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>
using namespace std;
const int MAX_SIZE = 20;
const int TOTAL_AID = 4;
void discard_line(ifstream &in);
void print(int print[][4] , int size);
int main()
{
//string evnt_id[MAX_SIZE]; //stores event id
int athlete_id[MAX_SIZE][TOTAL_AID]; //stores columns for athelete id
int total_records;
char c;
ifstream reg;
reg.open("C:\\result.txt");
discard_line(reg);
total_records = 0;
while( !reg.eof() )
{
for (int i = 0; i < TOTAL_AID; i++)
{
reg >> athlete_id[total_records][i] ;//read aid coloumns
}
total_records++;
reg.get(c);
}
reg.close();
print(athlete_id, total_records);
system("pause");
return 0;
}
void discard_line(ifstream &in)
{
char c;
do
in.get(c);
while (c!='\n');
}
void print(int print[][4] , int size)
{
cout << " \tID \t AID " << endl;
for (int i = 0; i < size; i++)
{
for (int j = 0; j < TOTAL_AID; j++)
{
cout << print[i][j] << endl;
}
}
}
You are printing std::endl after each number. If you want to have 1 row per line, then you should print std::endl after each row. Example:
#include <iostream>
int main(void)
{
int myArray[][4] = { {1,2,3,4}, {5,6,7,8} };
int width = 4, height = 2;
for (int i = 0; i < height; ++i)
{
for (int j = 0; j < width; ++j)
{
std::cout << myArray[i][j] << ' ';
}
std::cout << std::endl;
}
}
Also note that writing using namespace std; at the beginning of your files is considered bad practice since it causes some of user-defined names (of types, functions, etc.) to become ambiguous. If you want to avoid exhausting prefixing with std::, use using namespace std; within small scopes so that other functions and other files are not affected.
It is not only mistake that you miss the "endl".
The program will also skip the first line in the source file because of calling the function discard_line(reg), so you only can get the others data(5 6 7 8). It is not necessary to use the function at all.
in addition, make sure that you init the array and check boundary of array, such as MAX_SIZE, to guarantee the input data not to overflow the array.
you can do it like this
#include <iostream>
int your_array[2][4] = {
{1,2,3,4},
{5,6,7,8}
};
using namespace std;
int main() {
// get array columns and rows
int rows = sizeof your_array / sizeof your_array[0];
int cols = sizeof your_array[0] / sizeof(int);
// Print 2d Array
cout << "your_array data "<<endl<<endl;
for (int i = 0; i < rows; ++i)
{
for (int j = 0; j < cols; ++j)
{
std::cout << your_array[i][j] << std::endl;
}
// std::cout << std::endl;
}
}
output
1
2
3
4
5
6
7
8

How do I print out a simple array with numbers 0-99 on the console

I'm new to CS and I'm stuck on a practice problem in arrays where I have to print out an array with numbers 0-99 onto the console. My code right now seems to just create the numbers and print them but not actually put them in the array. I'm just curious how to actually set the elements to the array and then print them because that's the only thing holding me back from finishing the rest of the problem.
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
int num[100];
for (int i = 0; i < 100; i++)
num[i] = 0;
cout << num << endl;
}
Looks like you are very close! You just need to assign the value of 'i' into your array slot. Hope this helps!
EDIT:
To print the contents of the array you need to iterate back over the array and print each array element.
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
int num[100];
for (int i = 0; i < 100; i++)
num[i] = i; //assign value of 'i' to array slot
//print array elements
for (int i = 0; i < 100; i++)
cout << num[i]<< endl;
}
read the correct carefully:
#include <iostream>
#include <cstdio> // its C++ equivalent
using namespace std;
int main() {
int num[100];
for (int i = 0; i < 100; ++i)
num[i] = i;
for (int i = 0; i < 100; ++i)
cout << "num[" << i << "]" << num[i] << endl;
}

Filling an 1D array in C++

I have an integer array:
int listint[10] = {1,2,2,2,4,4,5,5,7,7,};
What I want to do is to create another array in terms of the multiplicity. So I define another array by:
int multi[7]={0};
the first index of the multi array multi[0] will tell us the number of multiplicity of the array listint that has zero. We can easily see that, there is no zero in the array listint, therefore the first member would be 0. Second would be 1 spice there are only 1 member in the array. Similarly multi[2] position is the multiplicity of 2 in the listint, which would be 3, since there are three 2 in the listint.
I want to use an for loop to do this thing.
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
unsigned int count;
int j;
int listint[10] = { 1,2,2,2,4,4,5,5,7,7, };
int multi[7] = { 0 };
for (int i = 0; i < 9; i++)
{
if (i == listint[i])
count++;
j = count;
multi[j] = 1;
}
cout << "multi hit \n" << multi[1] << endl;
return 0;
}
After running this code, I thought that I would want the multiplicity of the each element of the array of listint. So i tried to work with 2D array.
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
unsigned int count;
int i, j;
int listint[10] = { 1,2,2,2,4,4,5,5,7,7, };
int multi[7][10] = { 0 };
for (int i = 0; i < 9; i++)
{
if (i == listint[i])
count++;
j = count;
for (j = 0; j < count; j++) {
multi[j][i] = 1;
}
}
cout << "multi hit \n" << multi[4][i] << endl;
return 0;
}
The first code block is something that I wanted to print out the multiplicity. But later I found that, I want in a array that multiplicity of each elements. SO isn't the 2D array would be good idea?
I was not successful running the code using 2D array.
Another question. When I assign j = count, I mean that that's the multiplicity. so if the value of count is 2; I would think that is a multiplicity of two of any element in the array listint.
A 2d array is unnecessary if you're just trying to get the count of each element in a list.
#include <iostream>
int main() {
int listint[10] = { 1,2,2,2,4,4,5,5,7,7, };
int multi[8] = { 0 };
for (int i : listint)
++multi[i];
for (int i = 0; i < 8; ++i)
std::cout << i << ": " << multi[i] << '\n';
return 0;
}
There's also a simpler and better way of doing so using the standard collection std::map. Notably, this doesn't require you to know what the largest element in the array is beforehand:
#include <map>
#include <iostream>
int main() {
int listint[10] = {1,2,2,2,4,4,5,5,7,7,};
std::map<int, int> multi;
for (int i : listint)
multi[i]++;
for (auto [k,v] : multi)
std::cout << k << ": " << v << '\n';
}
Try this incase maps won't work for you since you're a beginner, simple:
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
unsigned int count;
int j;
int listint[10] = {1,2,2,2,4,4,5,5,7,7};
int multi[8]={0};
for(int i=0; i<10; i++)
{
multi[listint[i]]++; // using listint arrays elements as index of multi to increase count.
}
for( int i=1; i<8; i++)
{
cout << "multi hit of "<<i<<" : "<< multi[i]<<endl;
}
return 0;
}
OR if numbers could get large and are unknown but sorted
#include <iostream>:
#include <stdio.h>
using namespace std;
int main()
{
unsigned int count = 0;
int index = 0; // used to fill elements in below arrays
int Numbers[10] = {0}; // storing unique numbers like 1,2,4,5,7...
int Count[10] = {0}; // storing their counts like 1,3,2,2,2...
int listint[10] = {1, 2, 2, 2, 4, 4, 5, 5, 7, 7};
for(int i = 0; i < sizeof(listint) / sizeof(listint[0]); i++)
{
count++;
if (listint[i] != listint[i+1]) {
Numbers[index] = listint[i];
Count[index] = count;
count=0;
index++;
}
}
for(int i=0; i<index; i++)
{
cout << "multi hit of "<<Numbers[i]<<" is " << Count[i]<<endl;
}
return 0;
}

Calculating the inverse of a 3x3 Matrix, cannot use previous matrix to calculate inverse [duplicate]

I am trying to print a text file out on screen using arrays, but I'm not sure why it does not appear the way it is in the text file.
The text file:
1 2 3 4
5 6 7 8
Displayed on the screen as follows after applying discard function:
1
2
3
4
5
6
7
8
The code:
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>
using namespace std;
const int MAX_SIZE = 20;
const int TOTAL_AID = 4;
void discard_line(ifstream &in);
void print(int print[][4] , int size);
int main()
{
//string evnt_id[MAX_SIZE]; //stores event id
int athlete_id[MAX_SIZE][TOTAL_AID]; //stores columns for athelete id
int total_records;
char c;
ifstream reg;
reg.open("C:\\result.txt");
discard_line(reg);
total_records = 0;
while( !reg.eof() )
{
for (int i = 0; i < TOTAL_AID; i++)
{
reg >> athlete_id[total_records][i] ;//read aid coloumns
}
total_records++;
reg.get(c);
}
reg.close();
print(athlete_id, total_records);
system("pause");
return 0;
}
void discard_line(ifstream &in)
{
char c;
do
in.get(c);
while (c!='\n');
}
void print(int print[][4] , int size)
{
cout << " \tID \t AID " << endl;
for (int i = 0; i < size; i++)
{
for (int j = 0; j < TOTAL_AID; j++)
{
cout << print[i][j] << endl;
}
}
}
You are printing std::endl after each number. If you want to have 1 row per line, then you should print std::endl after each row. Example:
#include <iostream>
int main(void)
{
int myArray[][4] = { {1,2,3,4}, {5,6,7,8} };
int width = 4, height = 2;
for (int i = 0; i < height; ++i)
{
for (int j = 0; j < width; ++j)
{
std::cout << myArray[i][j] << ' ';
}
std::cout << std::endl;
}
}
Also note that writing using namespace std; at the beginning of your files is considered bad practice since it causes some of user-defined names (of types, functions, etc.) to become ambiguous. If you want to avoid exhausting prefixing with std::, use using namespace std; within small scopes so that other functions and other files are not affected.
It is not only mistake that you miss the "endl".
The program will also skip the first line in the source file because of calling the function discard_line(reg), so you only can get the others data(5 6 7 8). It is not necessary to use the function at all.
in addition, make sure that you init the array and check boundary of array, such as MAX_SIZE, to guarantee the input data not to overflow the array.
you can do it like this
#include <iostream>
int your_array[2][4] = {
{1,2,3,4},
{5,6,7,8}
};
using namespace std;
int main() {
// get array columns and rows
int rows = sizeof your_array / sizeof your_array[0];
int cols = sizeof your_array[0] / sizeof(int);
// Print 2d Array
cout << "your_array data "<<endl<<endl;
for (int i = 0; i < rows; ++i)
{
for (int j = 0; j < cols; ++j)
{
std::cout << your_array[i][j] << std::endl;
}
// std::cout << std::endl;
}
}
output
1
2
3
4
5
6
7
8

Displaying 2 iterated arrays in one for loop

I am working on creating a simulation of a test that will
1. randomize multiple choice answers
2. display the choices from a) b) c) d)
I have both codes done separately however can I use on for-loop to go about displaying this? Is this the best way to do this? All help is appreciated thank you!
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main (){
const int TEST_SIZE = 13;
srand(time(0));
string animals[TEST_SIZE] = {"dog","cat","fish","elephant","rhinoceros","cheetah","tiger","lion","zebra","giraffes","alligators","sloths","kangaroos" };
for (int i = 0; i < TEST_SIZE; i++){
//generate random index number (0,1,2,3,4,5...)
int index = rand() % FACE_SIZE;
//swap animals[i] with animals[index]
string temp = animals[i];
animals[i] = animals[index];
animals[index] = temp;
}
//loop through array and print values
for (int i = 0; i < 7; i++){
cout << animals[i] << " ";
}
}
//separate code for part 2: choices from a-g
#include <iostream>
#include <string>
using namespace std;
int main()
{
const int CHOICE_SIZE = 7;
string choices[] = { "a)", "b)","c)","d)","e)","f)","g)" };
for (int i = 0; i < CHOICE_SIZE; i++) {
cout << choices[i] << " ";
}
}
You can iterate over both arrays and stop when smaller will ends
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main (){
const int TEST_SIZE = 13;
srand(time(0));
string animals[TEST_SIZE] = {"dog","cat","fish","elephant","rhinoceros","cheetah","tiger","lion","zebra","giraffes","alligators","sloths","kangaroos" };
for (int i = 0; i < TEST_SIZE; i++){
//generate random index number (0,1,2,3,4,5...)
int index = rand() % FACE_SIZE; // maybe here should be TEST_SIZE?
//swap animals[i] with animals[index]
string temp = animals[i];
animals[i] = animals[index];
animals[index] = temp;
}
//loop through array and print values
for (int i = 0; i < 7; i++){
cout << animals[i] << " ";
}
const int CHOICE_SIZE = 7;
string choices[] = { "a)", "b)","c)","d)","e)","f)","g)" };
for (int i = 0; i < CHOICE_SIZE && i < TEST_SIZE; i++) {
cout << choices[i] << " " << animals[i] << ", ";
}
}
Also, consider that if you want to use fixed-size array, you can use std::array:
#include <array>
std::array<string, TEST_SIZE> animals = {...};
And for shuffling you can use std::shuffle from 'algorithm' header .