[英]Not able to print or access last character of a char array in c++
我試圖將句子的單個字符(包括空格)存儲在像“做或死”這樣的字符數組中,但是每當我打印數組(字符 arr)時,它都不會打印數組中的最后一個字符,即“e”。
有人可以告訴為什么會這樣。 我是 C++ 的初學者。
#include<iostream>
using namespace std;
int main()
{
int n;
cout << "Enter the length of the array\n";
cin >> n;
char arr[n + 1];
cin.ignore(n, '\n');
cout << "Enter the characters of the array\n";
cin.getline(arr, n);
for(int i = 0; i < n; i++)
cout << arr[i] << endl;
return 0;
}
因此,如果您將此cin.getline(arr, n)
更改為cin.getline(arr, n+1)
this,它將完美運行。
首先在 C++ 中,數組的大小必須是編譯時常量。因此,以以下代碼片段為例:
int n = 10;
int arr[n]; //INCORRECT because n is not a constant expression
正確的寫法是:
const int n = 10;
int arr[n]; //CORRECT
同樣,以下(您在代碼示例中所做的)不正確:
int n;
cout << "Enter the length of the array\n";
cin >> n;
char arr[n + 1]; //INCORRECT
其次,您沒有在屏幕上打印最后一個字符的原因是數組的大小是n+1
但在您的 for 循環中:
for(int i = 0; i < n; i++)
你只會達到 n。 您應該將上述內容替換為:
for(int i = 0; i < n + 1; i++)// note that +1 ADDED HERE
更好的解決方案是將std::string
用於您的目的,如下所示:
#include<iostream>
int main()
{
std::string inputString;
std::cout << "Enter the string"<<std::endl;
std::getline(std::cin, inputString);
//first way to print the string
std::cout << inputString << std::endl;
//second way to print the string
for(int i = 0; i < inputString.size(); ++i)
{
std::cout << inputString[i];
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.