![](/img/trans.png)
[英]C2440: '=': cannot convert from 'const char [9]' to 'char*'
[英]error C2440: '=' : cannot convert from 'const char [2]' to 'char'
我正在學習c ++,而且我在做一些新手的事情時遇到了問題。 我正在嘗試創建一個非常小的應用程序,它接受用戶輸入並將其存儲到char數組中。 然后我解析該數組並刪除所有括號和數據並顯示它。 如下
(325)858-7455來
3258587455
但我收到了錯誤
error C2440: '=' : cannot convert from 'const char [2]' to 'char'
下面是我的簡單代碼,可以很容易地在編譯器中拋出並運行。
#include "stdafx.h"
#include<iostream>
#include<conio.h>
using namespace std;
/*
This is a template Project
*/
int main()
{
char phoneNum[25];
for(int i = 0; i < (sizeof(phoneNum) / sizeof(char)); i++)
{
phoneNum[i] = "i";
}
cout<< "Enter a phone Number" <<endl;
cin>>phoneNum;
if(phoneNum[0] != '(' || phoneNum[4] != ')' || phoneNum[8] != '-')
{
cout<<"error";
}
else
{
for(int i = 0; i < (sizeof(phoneNum) / sizeof(char));i++)
{
if(phoneNum[i] != '(' || phoneNum[i] != ')' || phoneNum[i] != '-')
{
cout<<phoneNum[i];
}
}
}
cin>>phoneNum;
getchar();
return 0;
}
它沒有完全完成,所以如果有人有關於從字符串中刪除字符串字符的最佳方法的任何指針。 那太好了。
問題出在這里,我相信:
phoneNum[i] = "i";
您想要分配單個字符 ,因此您需要為文字使用單引號:
phoneNum[i] = 'i';
可能還有其他問題 - 我只是試圖修復標題中提到的問題:)
這里重要的是要理解"i"
和'i'
之間的區別。
"i"
是一個字符串,字符串作為char值序列存儲在內存中,在字符串的末尾附加一個空字符(假設為零)。 因此,當你寫"hello"
你正在存儲'h' 'e' 'l' 'l' 'o' '(null)'
。 以同樣的方式,當你寫"i"
,你正在存儲'i' '(null)'
,那就是'const char [2]'
(一個包含2個char元素的數組)。
當你使用'char數組'並使用[]運算符時,你指的是該數組中的'char'
元素。 所以當你寫phoneNum[i]
你會得到一個'char'
。
這就是你需要寫phoneNum[i] = 'i';
我建議使用C ++字符串和流:
#include <string>
#include <iostream>
#include <cstdlib>
using std::string;
using std::cout;
using std::endl;
using std::cerr;
using std::cin;
using std::flush;
int main(void)
{
string phone_number;
cout << "Enter phone number: " << flush;
getline(cin, phone_number);
// Check first for valid characters
const string valid_characters = "0123456789()- ";
string::size_type position = phone_number.find_first_not_of(valid_characters);
if (position != string::npos)
{
cerr << "Invalid phone number.\n";
return EXIT_FAILURE;
}
// Remove non-numeric characters
const string chars_to_remove = " ()-";
position = 0;
while ((position = phone_number.find_first_of(chars_to_remove, position))
!= string::npos)
{
phone_number.erase(position, 1);
}
cout << "\nPhone number only digits: " << phone_number << endl;
return EXIT_SUCCESS;
}
std::string
有許多用於操作方法的有用方法。
Stack Overflow上許多有經驗的開發人員的建議是讓新手在使用C風格的字符串( char *
)之前學習使用C ++字符串( std::string
)。
phoneNum[i] = "i";
左邊的東西是char
; 右邊的東西是一個字符串,一個char
數組。 你想要'i'
在右邊。
你為什么需要這張支票? 如果他們想要輸入格式與您提供的非美國電話號碼有什么關系[意思是parens和破折號,但不限於(3)3-4]
if(phoneNum[0] != '(' || phoneNum[4] != ')' || phoneNum[8] != '-')
{
cout<<"error";
}
else
我會刪除那個塊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.