首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C++ 二維字串陣列定義與 scanf 讀取錯誤解決

     編輯:程式設計綜合問答

錯誤現場

string pour[100]; // 或 vector<string> pour(100);
for (int i = 0; i < a; i++) {
    scanf("%s", pour[i]); // 編譯錯誤或運行崩潰
}

錯誤訊息:cannot convert 'std::string*' to 'char*' 或 運行時 Access Violation。

根因分析

  1. std::string 非 POD 型別:內部封裝指標、長度、容量,**不能直接當作 char* 緩衝區**傳給 scanf。
  2. 未配置記憶體:若用 char* pour[100],每個指標需先 malloc/new 配置空間。

三種正確解法

方案一:改用 C++ 風格 cin(推薦)

vector<string> pour(a);
for (int i = 0; i < a; i++) {
    cin >> pour[i]; // 自動處理記憶體、長度、換行
}

方案二:保留 scanf,用 vector<string> + resize + &str[0]

vector<string> pour(a);
for (int i = 0; i < a; i++) {
    pour[i].resize(100);           // 預留 100 字元緩衝區
    scanf("%99s", &pour[i][0]);    // 讀入底層 char 陣列,限寬防溢位
    pour[i].shrink_to_fit();       // 可選:縮減多餘容量
}
  • &pour[i][0] 取得內部連續記憶體起始位址 (C++11 保證連續)。
  • %99s 限制讀取長度,留 1 位給 \0。

方案三:純 C 風格 char pour[100][100]

char pour[100][100];
for (int i = 0; i < a; i++) {
    scanf("%99s", pour[i]); // pour[i] 退化為 char*
}

括號匹配完整範例(C++ 風格)

#include <iostream>
#include <vector>
#include <stack>
#include <string>
using namespace std;

bool isValid(const string& s) {
    stack<char> st;
    for (char c : s) {
        if (c == '(' || c == '[' || c == '{') st.push(c);
        else if (c == ')' || c == ']' || c == '}') {
            if (st.empty()) return false;
            char top = st.top(); st.pop();
            if ((c == ')' && top != '(') ||
                (c == ']' && top != '[') ||
                (c == '}' && top != '{')) return false;
        }
    }
    return st.empty();
}

int main() {
    int n; cin >> n;
    vector<string> lines(n);
    for (int i = 0; i < n; i++) cin >> lines[i];
    for (auto& line : lines) 
        cout << (isValid(line) ? "Match" : "Mismatch") << '\n';
}

拒絕 C 風格字串操作,擁抱 std::string + iostream,才是現代 C++ 正道。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved